sessiontypes-distributed (empty) → 0.1.0
raw patch · 19 files changed
+3119/−0 lines, 19 filesdep +basedep +binarydep +bytestringsetup-changed
Dependencies added: base, binary, bytestring, distributed-process, distributed-static, exceptions, hspec, network-transport-tcp, rank1dynamic, sessiontypes, sessiontypes-distributed
Files
- ChangeLog +3/−0
- LICENSE +674/−0
- Setup.hs +2/−0
- sessiontypes-distributed.cabal +71/−0
- src/Control/Distributed/Session.hs +385/−0
- src/Control/Distributed/Session/Closure.hs +239/−0
- src/Control/Distributed/Session/Debug.hs +103/−0
- src/Control/Distributed/Session/Eval.hs +159/−0
- src/Control/Distributed/Session/Exception.hs +43/−0
- src/Control/Distributed/Session/Interactive.hs +57/−0
- src/Control/Distributed/Session/Lifted.hs +481/−0
- src/Control/Distributed/Session/Normalize.hs +91/−0
- src/Control/Distributed/Session/STChannel.hs +245/−0
- src/Control/Distributed/Session/Session.hs +81/−0
- src/Control/Distributed/Session/Spawn.hs +268/−0
- src/Control/Distributed/Session/Visualize.hs +9/−0
- test/Test/Lifted/Main.hs +55/−0
- test/Test/Program/Closure.hs +68/−0
- test/Test/Spawn/Main.hs +85/−0
+ ChangeLog view
@@ -0,0 +1,3 @@+2017-09-30 Ferdinand van Walree 0.1.0++* Initial release.
+ LICENSE view
@@ -0,0 +1,674 @@+ GNU GENERAL PUBLIC LICENSE+ Version 3, 29 June 2007++ Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>+ Everyone is permitted to copy and distribute verbatim copies+ of this license document, but changing it is not allowed.++ Preamble++ The GNU General Public License is a free, copyleft license for+software and other kinds of works.++ The licenses for most software and other practical works are designed+to take away your freedom to share and change the works. By contrast,+the GNU General Public License is intended to guarantee your freedom to+share and change all versions of a program--to make sure it remains free+software for all its users. We, the Free Software Foundation, use the+GNU General Public License for most of our software; it applies also to+any other work released this way by its authors. You can apply it to+your programs, too.++ When we speak of free software, we are referring to freedom, not+price. Our General Public Licenses are designed to make sure that you+have the freedom to distribute copies of free software (and charge for+them if you wish), that you receive source code or can get it if you+want it, that you can change the software or use pieces of it in new+free programs, and that you know you can do these things.++ To protect your rights, we need to prevent others from denying you+these rights or asking you to surrender the rights. Therefore, you have+certain responsibilities if you distribute copies of the software, or if+you modify it: responsibilities to respect the freedom of others.++ For example, if you distribute copies of such a program, whether+gratis or for a fee, you must pass on to the recipients the same+freedoms that you received. You must make sure that they, too, receive+or can get the source code. And you must show them these terms so they+know their rights.++ Developers that use the GNU GPL protect your rights with two steps:+(1) assert copyright on the software, and (2) offer you this License+giving you legal permission to copy, distribute and/or modify it.++ For the developers' and authors' protection, the GPL clearly explains+that there is no warranty for this free software. For both users' and+authors' sake, the GPL requires that modified versions be marked as+changed, so that their problems will not be attributed erroneously to+authors of previous versions.++ Some devices are designed to deny users access to install or run+modified versions of the software inside them, although the manufacturer+can do so. This is fundamentally incompatible with the aim of+protecting users' freedom to change the software. The systematic+pattern of such abuse occurs in the area of products for individuals to+use, which is precisely where it is most unacceptable. Therefore, we+have designed this version of the GPL to prohibit the practice for those+products. If such problems arise substantially in other domains, we+stand ready to extend this provision to those domains in future versions+of the GPL, as needed to protect the freedom of users.++ Finally, every program is threatened constantly by software patents.+States should not allow patents to restrict development and use of+software on general-purpose computers, but in those that do, we wish to+avoid the special danger that patents applied to a free program could+make it effectively proprietary. To prevent this, the GPL assures that+patents cannot be used to render the program non-free.++ The precise terms and conditions for copying, distribution and+modification follow.++ TERMS AND CONDITIONS++ 0. Definitions.++ "This License" refers to version 3 of the GNU General Public License.++ "Copyright" also means copyright-like laws that apply to other kinds of+works, such as semiconductor masks.++ "The Program" refers to any copyrightable work licensed under this+License. Each licensee is addressed as "you". "Licensees" and+"recipients" may be individuals or organizations.++ To "modify" a work means to copy from or adapt all or part of the work+in a fashion requiring copyright permission, other than the making of an+exact copy. The resulting work is called a "modified version" of the+earlier work or a work "based on" the earlier work.++ A "covered work" means either the unmodified Program or a work based+on the Program.++ To "propagate" a work means to do anything with it that, without+permission, would make you directly or secondarily liable for+infringement under applicable copyright law, except executing it on a+computer or modifying a private copy. Propagation includes copying,+distribution (with or without modification), making available to the+public, and in some countries other activities as well.++ To "convey" a work means any kind of propagation that enables other+parties to make or receive copies. Mere interaction with a user through+a computer network, with no transfer of a copy, is not conveying.++ An interactive user interface displays "Appropriate Legal Notices"+to the extent that it includes a convenient and prominently visible+feature that (1) displays an appropriate copyright notice, and (2)+tells the user that there is no warranty for the work (except to the+extent that warranties are provided), that licensees may convey the+work under this License, and how to view a copy of this License. If+the interface presents a list of user commands or options, such as a+menu, a prominent item in the list meets this criterion.++ 1. Source Code.++ The "source code" for a work means the preferred form of the work+for making modifications to it. "Object code" means any non-source+form of a work.++ A "Standard Interface" means an interface that either is an official+standard defined by a recognized standards body, or, in the case of+interfaces specified for a particular programming language, one that+is widely used among developers working in that language.++ The "System Libraries" of an executable work include anything, other+than the work as a whole, that (a) is included in the normal form of+packaging a Major Component, but which is not part of that Major+Component, and (b) serves only to enable use of the work with that+Major Component, or to implement a Standard Interface for which an+implementation is available to the public in source code form. A+"Major Component", in this context, means a major essential component+(kernel, window system, and so on) of the specific operating system+(if any) on which the executable work runs, or a compiler used to+produce the work, or an object code interpreter used to run it.++ The "Corresponding Source" for a work in object code form means all+the source code needed to generate, install, and (for an executable+work) run the object code and to modify the work, including scripts to+control those activities. However, it does not include the work's+System Libraries, or general-purpose tools or generally available free+programs which are used unmodified in performing those activities but+which are not part of the work. For example, Corresponding Source+includes interface definition files associated with source files for+the work, and the source code for shared libraries and dynamically+linked subprograms that the work is specifically designed to require,+such as by intimate data communication or control flow between those+subprograms and other parts of the work.++ The Corresponding Source need not include anything that users+can regenerate automatically from other parts of the Corresponding+Source.++ The Corresponding Source for a work in source code form is that+same work.++ 2. Basic Permissions.++ All rights granted under this License are granted for the term of+copyright on the Program, and are irrevocable provided the stated+conditions are met. This License explicitly affirms your unlimited+permission to run the unmodified Program. The output from running a+covered work is covered by this License only if the output, given its+content, constitutes a covered work. This License acknowledges your+rights of fair use or other equivalent, as provided by copyright law.++ You may make, run and propagate covered works that you do not+convey, without conditions so long as your license otherwise remains+in force. You may convey covered works to others for the sole purpose+of having them make modifications exclusively for you, or provide you+with facilities for running those works, provided that you comply with+the terms of this License in conveying all material for which you do+not control copyright. Those thus making or running the covered works+for you must do so exclusively on your behalf, under your direction+and control, on terms that prohibit them from making any copies of+your copyrighted material outside their relationship with you.++ Conveying under any other circumstances is permitted solely under+the conditions stated below. Sublicensing is not allowed; section 10+makes it unnecessary.++ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.++ No covered work shall be deemed part of an effective technological+measure under any applicable law fulfilling obligations under article+11 of the WIPO copyright treaty adopted on 20 December 1996, or+similar laws prohibiting or restricting circumvention of such+measures.++ When you convey a covered work, you waive any legal power to forbid+circumvention of technological measures to the extent such circumvention+is effected by exercising rights under this License with respect to+the covered work, and you disclaim any intention to limit operation or+modification of the work as a means of enforcing, against the work's+users, your or third parties' legal rights to forbid circumvention of+technological measures.++ 4. Conveying Verbatim Copies.++ You may convey verbatim copies of the Program's source code as you+receive it, in any medium, provided that you conspicuously and+appropriately publish on each copy an appropriate copyright notice;+keep intact all notices stating that this License and any+non-permissive terms added in accord with section 7 apply to the code;+keep intact all notices of the absence of any warranty; and give all+recipients a copy of this License along with the Program.++ You may charge any price or no price for each copy that you convey,+and you may offer support or warranty protection for a fee.++ 5. Conveying Modified Source Versions.++ You may convey a work based on the Program, or the modifications to+produce it from the Program, in the form of source code under the+terms of section 4, provided that you also meet all of these conditions:++ a) The work must carry prominent notices stating that you modified+ it, and giving a relevant date.++ b) The work must carry prominent notices stating that it is+ released under this License and any conditions added under section+ 7. This requirement modifies the requirement in section 4 to+ "keep intact all notices".++ c) You must license the entire work, as a whole, under this+ License to anyone who comes into possession of a copy. This+ License will therefore apply, along with any applicable section 7+ additional terms, to the whole of the work, and all its parts,+ regardless of how they are packaged. This License gives no+ permission to license the work in any other way, but it does not+ invalidate such permission if you have separately received it.++ d) If the work has interactive user interfaces, each must display+ Appropriate Legal Notices; however, if the Program has interactive+ interfaces that do not display Appropriate Legal Notices, your+ work need not make them do so.++ A compilation of a covered work with other separate and independent+works, which are not by their nature extensions of the covered work,+and which are not combined with it such as to form a larger program,+in or on a volume of a storage or distribution medium, is called an+"aggregate" if the compilation and its resulting copyright are not+used to limit the access or legal rights of the compilation's users+beyond what the individual works permit. Inclusion of a covered work+in an aggregate does not cause this License to apply to the other+parts of the aggregate.++ 6. Conveying Non-Source Forms.++ You may convey a covered work in object code form under the terms+of sections 4 and 5, provided that you also convey the+machine-readable Corresponding Source under the terms of this License,+in one of these ways:++ a) Convey the object code in, or embodied in, a physical product+ (including a physical distribution medium), accompanied by the+ Corresponding Source fixed on a durable physical medium+ customarily used for software interchange.++ b) Convey the object code in, or embodied in, a physical product+ (including a physical distribution medium), accompanied by a+ written offer, valid for at least three years and valid for as+ long as you offer spare parts or customer support for that product+ model, to give anyone who possesses the object code either (1) a+ copy of the Corresponding Source for all the software in the+ product that is covered by this License, on a durable physical+ medium customarily used for software interchange, for a price no+ more than your reasonable cost of physically performing this+ conveying of source, or (2) access to copy the+ Corresponding Source from a network server at no charge.++ c) Convey individual copies of the object code with a copy of the+ written offer to provide the Corresponding Source. This+ alternative is allowed only occasionally and noncommercially, and+ only if you received the object code with such an offer, in accord+ with subsection 6b.++ d) Convey the object code by offering access from a designated+ place (gratis or for a charge), and offer equivalent access to the+ Corresponding Source in the same way through the same place at no+ further charge. You need not require recipients to copy the+ Corresponding Source along with the object code. If the place to+ copy the object code is a network server, the Corresponding Source+ may be on a different server (operated by you or a third party)+ that supports equivalent copying facilities, provided you maintain+ clear directions next to the object code saying where to find the+ Corresponding Source. Regardless of what server hosts the+ Corresponding Source, you remain obligated to ensure that it is+ available for as long as needed to satisfy these requirements.++ e) Convey the object code using peer-to-peer transmission, provided+ you inform other peers where the object code and Corresponding+ Source of the work are being offered to the general public at no+ charge under subsection 6d.++ A separable portion of the object code, whose source code is excluded+from the Corresponding Source as a System Library, need not be+included in conveying the object code work.++ A "User Product" is either (1) a "consumer product", which means any+tangible personal property which is normally used for personal, family,+or household purposes, or (2) anything designed or sold for incorporation+into a dwelling. In determining whether a product is a consumer product,+doubtful cases shall be resolved in favor of coverage. For a particular+product received by a particular user, "normally used" refers to a+typical or common use of that class of product, regardless of the status+of the particular user or of the way in which the particular user+actually uses, or expects or is expected to use, the product. A product+is a consumer product regardless of whether the product has substantial+commercial, industrial or non-consumer uses, unless such uses represent+the only significant mode of use of the product.++ "Installation Information" for a User Product means any methods,+procedures, authorization keys, or other information required to install+and execute modified versions of a covered work in that User Product from+a modified version of its Corresponding Source. The information must+suffice to ensure that the continued functioning of the modified object+code is in no case prevented or interfered with solely because+modification has been made.++ If you convey an object code work under this section in, or with, or+specifically for use in, a User Product, and the conveying occurs as+part of a transaction in which the right of possession and use of the+User Product is transferred to the recipient in perpetuity or for a+fixed term (regardless of how the transaction is characterized), the+Corresponding Source conveyed under this section must be accompanied+by the Installation Information. But this requirement does not apply+if neither you nor any third party retains the ability to install+modified object code on the User Product (for example, the work has+been installed in ROM).++ The requirement to provide Installation Information does not include a+requirement to continue to provide support service, warranty, or updates+for a work that has been modified or installed by the recipient, or for+the User Product in which it has been modified or installed. Access to a+network may be denied when the modification itself materially and+adversely affects the operation of the network or violates the rules and+protocols for communication across the network.++ Corresponding Source conveyed, and Installation Information provided,+in accord with this section must be in a format that is publicly+documented (and with an implementation available to the public in+source code form), and must require no special password or key for+unpacking, reading or copying.++ 7. Additional Terms.++ "Additional permissions" are terms that supplement the terms of this+License by making exceptions from one or more of its conditions.+Additional permissions that are applicable to the entire Program shall+be treated as though they were included in this License, to the extent+that they are valid under applicable law. If additional permissions+apply only to part of the Program, that part may be used separately+under those permissions, but the entire Program remains governed by+this License without regard to the additional permissions.++ When you convey a copy of a covered work, you may at your option+remove any additional permissions from that copy, or from any part of+it. (Additional permissions may be written to require their own+removal in certain cases when you modify the work.) You may place+additional permissions on material, added by you to a covered work,+for which you have or can give appropriate copyright permission.++ Notwithstanding any other provision of this License, for material you+add to a covered work, you may (if authorized by the copyright holders of+that material) supplement the terms of this License with terms:++ a) Disclaiming warranty or limiting liability differently from the+ terms of sections 15 and 16 of this License; or++ b) Requiring preservation of specified reasonable legal notices or+ author attributions in that material or in the Appropriate Legal+ Notices displayed by works containing it; or++ c) Prohibiting misrepresentation of the origin of that material, or+ requiring that modified versions of such material be marked in+ reasonable ways as different from the original version; or++ d) Limiting the use for publicity purposes of names of licensors or+ authors of the material; or++ e) Declining to grant rights under trademark law for use of some+ trade names, trademarks, or service marks; or++ f) Requiring indemnification of licensors and authors of that+ material by anyone who conveys the material (or modified versions of+ it) with contractual assumptions of liability to the recipient, for+ any liability that these contractual assumptions directly impose on+ those licensors and authors.++ All other non-permissive additional terms are considered "further+restrictions" within the meaning of section 10. If the Program as you+received it, or any part of it, contains a notice stating that it is+governed by this License along with a term that is a further+restriction, you may remove that term. If a license document contains+a further restriction but permits relicensing or conveying under this+License, you may add to a covered work material governed by the terms+of that license document, provided that the further restriction does+not survive such relicensing or conveying.++ If you add terms to a covered work in accord with this section, you+must place, in the relevant source files, a statement of the+additional terms that apply to those files, or a notice indicating+where to find the applicable terms.++ Additional terms, permissive or non-permissive, may be stated in the+form of a separately written license, or stated as exceptions;+the above requirements apply either way.++ 8. Termination.++ You may not propagate or modify a covered work except as expressly+provided under this License. Any attempt otherwise to propagate or+modify it is void, and will automatically terminate your rights under+this License (including any patent licenses granted under the third+paragraph of section 11).++ However, if you cease all violation of this License, then your+license from a particular copyright holder is reinstated (a)+provisionally, unless and until the copyright holder explicitly and+finally terminates your license, and (b) permanently, if the copyright+holder fails to notify you of the violation by some reasonable means+prior to 60 days after the cessation.++ Moreover, your license from a particular copyright holder is+reinstated permanently if the copyright holder notifies you of the+violation by some reasonable means, this is the first time you have+received notice of violation of this License (for any work) from that+copyright holder, and you cure the violation prior to 30 days after+your receipt of the notice.++ Termination of your rights under this section does not terminate the+licenses of parties who have received copies or rights from you under+this License. If your rights have been terminated and not permanently+reinstated, you do not qualify to receive new licenses for the same+material under section 10.++ 9. Acceptance Not Required for Having Copies.++ You are not required to accept this License in order to receive or+run a copy of the Program. Ancillary propagation of a covered work+occurring solely as a consequence of using peer-to-peer transmission+to receive a copy likewise does not require acceptance. However,+nothing other than this License grants you permission to propagate or+modify any covered work. These actions infringe copyright if you do+not accept this License. Therefore, by modifying or propagating a+covered work, you indicate your acceptance of this License to do so.++ 10. Automatic Licensing of Downstream Recipients.++ Each time you convey a covered work, the recipient automatically+receives a license from the original licensors, to run, modify and+propagate that work, subject to this License. You are not responsible+for enforcing compliance by third parties with this License.++ An "entity transaction" is a transaction transferring control of an+organization, or substantially all assets of one, or subdividing an+organization, or merging organizations. If propagation of a covered+work results from an entity transaction, each party to that+transaction who receives a copy of the work also receives whatever+licenses to the work the party's predecessor in interest had or could+give under the previous paragraph, plus a right to possession of the+Corresponding Source of the work from the predecessor in interest, if+the predecessor has it or can get it with reasonable efforts.++ You may not impose any further restrictions on the exercise of the+rights granted or affirmed under this License. For example, you may+not impose a license fee, royalty, or other charge for exercise of+rights granted under this License, and you may not initiate litigation+(including a cross-claim or counterclaim in a lawsuit) alleging that+any patent claim is infringed by making, using, selling, offering for+sale, or importing the Program or any portion of it.++ 11. Patents.++ A "contributor" is a copyright holder who authorizes use under this+License of the Program or a work on which the Program is based. The+work thus licensed is called the contributor's "contributor version".++ A contributor's "essential patent claims" are all patent claims+owned or controlled by the contributor, whether already acquired or+hereafter acquired, that would be infringed by some manner, permitted+by this License, of making, using, or selling its contributor version,+but do not include claims that would be infringed only as a+consequence of further modification of the contributor version. For+purposes of this definition, "control" includes the right to grant+patent sublicenses in a manner consistent with the requirements of+this License.++ Each contributor grants you a non-exclusive, worldwide, royalty-free+patent license under the contributor's essential patent claims, to+make, use, sell, offer for sale, import and otherwise run, modify and+propagate the contents of its contributor version.++ In the following three paragraphs, a "patent license" is any express+agreement or commitment, however denominated, not to enforce a patent+(such as an express permission to practice a patent or covenant not to+sue for patent infringement). To "grant" such a patent license to a+party means to make such an agreement or commitment not to enforce a+patent against the party.++ If you convey a covered work, knowingly relying on a patent license,+and the Corresponding Source of the work is not available for anyone+to copy, free of charge and under the terms of this License, through a+publicly available network server or other readily accessible means,+then you must either (1) cause the Corresponding Source to be so+available, or (2) arrange to deprive yourself of the benefit of the+patent license for this particular work, or (3) arrange, in a manner+consistent with the requirements of this License, to extend the patent+license to downstream recipients. "Knowingly relying" means you have+actual knowledge that, but for the patent license, your conveying the+covered work in a country, or your recipient's use of the covered work+in a country, would infringe one or more identifiable patents in that+country that you have reason to believe are valid.++ If, pursuant to or in connection with a single transaction or+arrangement, you convey, or propagate by procuring conveyance of, a+covered work, and grant a patent license to some of the parties+receiving the covered work authorizing them to use, propagate, modify+or convey a specific copy of the covered work, then the patent license+you grant is automatically extended to all recipients of the covered+work and works based on it.++ A patent license is "discriminatory" if it does not include within+the scope of its coverage, prohibits the exercise of, or is+conditioned on the non-exercise of one or more of the rights that are+specifically granted under this License. You may not convey a covered+work if you are a party to an arrangement with a third party that is+in the business of distributing software, under which you make payment+to the third party based on the extent of your activity of conveying+the work, and under which the third party grants, to any of the+parties who would receive the covered work from you, a discriminatory+patent license (a) in connection with copies of the covered work+conveyed by you (or copies made from those copies), or (b) primarily+for and in connection with specific products or compilations that+contain the covered work, unless you entered into that arrangement,+or that patent license was granted, prior to 28 March 2007.++ Nothing in this License shall be construed as excluding or limiting+any implied license or other defenses to infringement that may+otherwise be available to you under applicable patent law.++ 12. No Surrender of Others' Freedom.++ If conditions are imposed on you (whether by court order, agreement or+otherwise) that contradict the conditions of this License, they do not+excuse you from the conditions of this License. If you cannot convey a+covered work so as to satisfy simultaneously your obligations under this+License and any other pertinent obligations, then as a consequence you may+not convey it at all. For example, if you agree to terms that obligate you+to collect a royalty for further conveying from those to whom you convey+the Program, the only way you could satisfy both those terms and this+License would be to refrain entirely from conveying the Program.++ 13. Use with the GNU Affero General Public License.++ Notwithstanding any other provision of this License, you have+permission to link or combine any covered work with a work licensed+under version 3 of the GNU Affero General Public License into a single+combined work, and to convey the resulting work. The terms of this+License will continue to apply to the part which is the covered work,+but the special requirements of the GNU Affero General Public License,+section 13, concerning interaction through a network will apply to the+combination as such.++ 14. Revised Versions of this License.++ The Free Software Foundation may publish revised and/or new versions of+the GNU General Public License from time to time. Such new versions will+be similar in spirit to the present version, but may differ in detail to+address new problems or concerns.++ Each version is given a distinguishing version number. If the+Program specifies that a certain numbered version of the GNU General+Public License "or any later version" applies to it, you have the+option of following the terms and conditions either of that numbered+version or of any later version published by the Free Software+Foundation. If the Program does not specify a version number of the+GNU General Public License, you may choose any version ever published+by the Free Software Foundation.++ If the Program specifies that a proxy can decide which future+versions of the GNU General Public License can be used, that proxy's+public statement of acceptance of a version permanently authorizes you+to choose that version for the Program.++ Later license versions may give you additional or different+permissions. However, no additional obligations are imposed on any+author or copyright holder as a result of your choosing to follow a+later version.++ 15. Disclaimer of Warranty.++ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY+APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT+HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY+OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,+THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR+PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM+IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF+ALL NECESSARY SERVICING, REPAIR OR CORRECTION.++ 16. Limitation of Liability.++ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS+THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY+GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE+USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF+DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD+PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),+EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF+SUCH DAMAGES.++ 17. Interpretation of Sections 15 and 16.++ If the disclaimer of warranty and limitation of liability provided+above cannot be given local legal effect according to their terms,+reviewing courts shall apply local law that most closely approximates+an absolute waiver of all civil liability in connection with the+Program, unless a warranty or assumption of liability accompanies a+copy of the Program in return for a fee.++ END OF TERMS AND CONDITIONS++ How to Apply These Terms to Your New Programs++ If you develop a new program, and you want it to be of the greatest+possible use to the public, the best way to achieve this is to make it+free software which everyone can redistribute and change under these terms.++ To do so, attach the following notices to the program. It is safest+to attach them to the start of each source file to most effectively+state the exclusion of warranty; and each file should have at least+the "copyright" line and a pointer to where the full notice is found.++ {one line to give the program's name and a brief idea of what it does.}+ Copyright (C) {year} {name of author}++ This program is free software: you can redistribute it and/or modify+ it under the terms of the GNU General Public License as published by+ the Free Software Foundation, either version 3 of the License, or+ (at your option) any later version.++ This program is distributed in the hope that it will be useful,+ but WITHOUT ANY WARRANTY; without even the implied warranty of+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ GNU General Public License for more details.++ You should have received a copy of the GNU General Public License+ along with this program. If not, see <http://www.gnu.org/licenses/>.++Also add information on how to contact you by electronic and paper mail.++ If the program does terminal interaction, make it output a short+notice like this when it starts in an interactive mode:++ {project} Copyright (C) {year} {fullname}+ This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.+ This is free software, and you are welcome to redistribute it+ under certain conditions; type `show c' for details.++The hypothetical commands `show w' and `show c' should show the appropriate+parts of the General Public License. Of course, your program's commands+might be different; for a GUI interface, you would use an "about box".++ You should also get your employer (if you work as a programmer) or school,+if any, to sign a "copyright disclaimer" for the program, if necessary.+For more information on this, and how to apply and follow the GNU GPL, see+<http://www.gnu.org/licenses/>.++ The GNU General Public License does not permit incorporating your program+into proprietary programs. If your program is a subroutine library, you+may consider it more useful to permit linking proprietary applications with+the library. If this is what you want to do, use the GNU Lesser General+Public License instead of this License. But first, please read+<http://www.gnu.org/philosophy/why-not-lgpl.html>.
+ Setup.hs view
@@ -0,0 +1,2 @@+import Distribution.Simple+main = defaultMain
+ sessiontypes-distributed.cabal view
@@ -0,0 +1,71 @@+name: sessiontypes-distributed+version: 0.1.0+synopsis: Session types distributed+description: This package serves as a wrapper over both the Cloud Haskell library (distributed-process) and the sessiontypes library.+ It provides an interpreter for evaluating session typed programs to Cloud Haskell programs and exposes several combinators for spawning sessions.+homepage: https://github.com/Ferdinand-vW/sessiontypes-distributed#readme+license: GPL-3+license-file: LICENSE+author: Ferdinand van Walree+maintainer: Ferdinand van Walree+copyright: 2017 Ferdinand van Walree+category: Control+build-type: Simple+extra-source-files: ChangeLog+cabal-version: >=1.10++library+ hs-source-dirs: src+ exposed-modules: Control.Distributed.Session+ , Control.Distributed.Session.Debug+ , Control.Distributed.Session.Eval+ , Control.Distributed.Session.Exception+ , Control.Distributed.Session.Lifted+ , Control.Distributed.Session.Interactive+ , Control.Distributed.Session.Visualize+ , Control.Distributed.Session.Normalize+ , Control.Distributed.Session.Session+ , Control.Distributed.Session.Spawn+ , Control.Distributed.Session.Closure+ , Control.Distributed.Session.STChannel+ build-depends: base >= 4.7 && < 5+ , sessiontypes >= 0.1.0 && < 0.2.0+ , binary >= 0.8.3 && < 0.9.0+ , bytestring >= 0.10.8.1 && < 0.11+ , distributed-process >= 0.7.3 && < 0.8+ , distributed-static >= 0.3.8 && < 0.4+ , exceptions >= 0.8.3 && < 0.9.0+ , rank1dynamic >= 0.3.3 && < 0.4+ default-language: Haskell2010++test-suite sessiontypes-distributed-spawn+ type: exitcode-stdio-1.0+ hs-source-dirs: test+ main-is: Test/Spawn/Main.hs+ other-modules: Test.Program.Closure+ build-depends: base >= 4.7 && < 5+ , sessiontypes-distributed+ , sessiontypes >= 0.1.0 && < 0.2.0+ , hspec >= 2.4.4 && < 2.5+ , distributed-process >= 0.7.3 && < 0.8+ , network-transport-tcp >= 0.5.1 && < 0.6+ ghc-options: -threaded -rtsopts -with-rtsopts=-N+ default-language: Haskell2010++test-suite sessiontypes-distributed-lifted+ type: exitcode-stdio-1.0+ hs-source-dirs: test+ main-is: Test/Lifted/Main.hs+ other-modules: Test.Program.Closure+ build-depends: base >= 4.7 && < 5+ , sessiontypes-distributed+ , sessiontypes >= 0.1.0 && < 0.2.0+ , hspec >= 2.4.4 && < 2.5+ , distributed-process >= 0.7.3 && < 0.8+ , network-transport-tcp >= 0.5.1 && < 0.6+ ghc-options: -threaded -rtsopts -with-rtsopts=-N+ default-language: Haskell2010++source-repository head+ type: git+ location: https://github.com/Ferdinand-vW/sessiontypes-distributed
+ src/Control/Distributed/Session.hs view
@@ -0,0 +1,385 @@+-- | This package defines a wrapper over the sessiontypes library that allows for evaluating session typed programs to Cloud Haskell programs.+--+-- The goal of this library is to allow a user to define two dual session typed programs, spawn two processes and have these processes evaluate the programs.+--+-- Session types guarantee that the resulting Cloud Haskell programs correctly implement the protocol and that they are non-deadlocking.+--+-- We define a session typed program with an indexed monad `Session` that is both a reader monad and a wrapper over a `STTerm` that uses `Process` as its underlying monad.+-- +-- This module exports the most important parts of this library:+--+-- * "Control.Distributed.Session.Session": Defines the `Session` monad and `SessionInfo` that is used as the environment of `Session`.+-- * "Control.Distributed.Session.Eval": Defines the interpreter for evaluation a `Session` to a `Process`.+-- * "Control.Distributed.Session.Spawn": Defines several combinators for spawning sessions.+-- * "Control.Distributed.Session.Closure": Module for constructing closures of sessions.+-- * "Control.Distributed.Session.STChannel": Session typed channel that allows for transmitting values of different types.+-- * "Control.Distributed.Session.Lifted": Exports lifted functions from the distributed-process package. +--+-- Additionally we defined wrappers for using the interpreters defined in the sessiontypes package on a `Session`:+--+-- * "Control.Distributed.Session.Debug"+-- * "Control.Distributed.Session.Interactive"+-- * "Control.Distributed.Session.Normalize"+-- * "Control.Distributed.Session.Visualize"+module Control.Distributed.Session (+ -- * Core+ module Control.SessionTypes,+ -- * Session+ -- ** Data types+ Session(..),+ SessionInfo(..),+ runSession,+ -- ** Lifting+ liftP,+ liftST,+ -- * Spawning sessions+ -- ** Call+ callLocalSessionP,+ callLocalSession,+ callRemoteSessionP,+ callRemoteSession,+ callRemoteSessionP',+ callRemoteSession',+ -- ** Spawn+ spawnLLSessionP,+ spawnLLSession,+ spawnLRSessionP,+ spawnLRSession,+ spawnRRSessionP,+ spawnRRSession,+ -- * Eval+ evalSession,+ evalSessionEq,+ evalSessionEq',+ -- * Closures+ -- ** Encapsulation+ SpawnSession (..),+ SessionWrap (..),+ -- ** RemoteTable+ sessionRemoteTable,+ -- ** Static and Closures+ -- *** Singular+ remoteSessionStatic,+ remoteSessionClosure,+ remoteSessionStatic',+ remoteSessionClosure',+ -- *** SpawnChannel+ spawnChannelStatic,+ spawnChannelClosure,+ -- *** Local Remote Evaluation+ evalLocalSession,+ remoteSpawnSessionStatic,+ remoteSpawnSessionClosure,+ remoteSpawnSessionStatic',+ remoteSpawnSessionClosure',+ -- *** Remote Remote Evaluation+ rrSpawnSessionSendStatic,+ rrSpawnSessionSendClosure,+ rrSpawnSessionExpectStatic,+ rrSpawnSessionExpectClosure,+ -- * STChannel+ -- ** Data types+ Message(..),+ STSendPort(..),+ STReceivePort(..),+ -- ** Type synonyms+ STChan,+ STChanBi,+ UTChan,+ -- ** Create+ newSTChan,+ newSTChanBi,+ newUTChan,+ toSTChan,+ toSTChanBi,+ sendProxy,+ recvProxy,+ -- ** Usage+ sendSTChan,+ recvSTChan,+ STSplit(..),+ STRec(..),+ -- ** Channel transformer+ STChannelT(..),+ sendSTChanM,+ recvSTChanM,+ sel1ChanM,+ sel2ChanM,+ off1ChanM,+ off2ChanM,+ recChanM,+ wkChanM,+ varChanM,+ epsChanM,+ -- * Lifted+ utsend,+ usend,+ expect,+ expectTimeout,+ newChan,+ sendChan,+ receiveChan,+ receiveChanTimeout,+ mergePortsBiased,+ mergePortsRR,+ unsafeSend,+ unsafeSendChan,+ unsafeNSend,+ unsafeNSendRemote,+ receiveWait,+ receiveTimeout,+ unwrapMessage,+ handleMessage,+ handleMessage_,+ handleMessageP,+ handleMessageP_,+ handleMessageIf,+ handleMessageIf_,+ handleMessageIfP,+ handleMessageIfP_,+ forward,+ uforward,+ delegate,+ relay,+ proxy,+ proxyP,+ spawn,+ spawnP,+ call,+ callP,+ terminate,+ die,+ kill,+ exit,+ catchExit,+ catchExitP,+ catchesExit,+ catchesExitP,+ getSelfPid,+ getSelfNode,+ getOthPid,+ getOthNode,+ getProcessInfo,+ getNodeStats,+ link,+ linkNode,+ unlink,+ unlinkNode,+ monitor,+ monitorNode,+ monitorPort,+ unmonitor,+ withMonitor,+ withMonitor_,+ withMonitorP,+ withMonitorP_,+ unStatic,+ unClosure,+ say,+ register,+ unregister,+ whereis,+ nsend,+ registerRemoteAsync,+ reregisterRemoteAsync,+ whereisRemoteAsync,+ nsendRemote,+ spawnAsync,+ spawnAsyncP,+ spawnSupervised,+ spawnSupervisedP,+ spawnLink,+ spawnLinkP,+ spawnMonitor,+ spawnMonitorP,+ spawnChannel,+ spawnChannelP,+ spawnLocal,+ spawnLocalP,+ spawnChannelLocal,+ spawnChannelLocalP,+ callLocal,+ callLocalP,+ reconnect,+ reconnectPort+) where++++import Control.SessionTypes++import Control.Distributed.Session.Session (+ Session(..),+ SessionInfo(..),+ runSession,+ liftP,+ liftST+ )++import Control.Distributed.Session.Exception ()++import Control.Distributed.Session.Spawn (+ callLocalSessionP,+ callLocalSession,+ callRemoteSessionP,+ callRemoteSession,+ callRemoteSessionP',+ callRemoteSession',+ spawnLLSessionP,+ spawnLLSession,+ spawnLRSessionP,+ spawnLRSession,+ spawnRRSessionP,+ spawnRRSession+ )++import Control.Distributed.Session.Eval (+ evalSession,+ evalSessionEq,+ evalSessionEq'+ )++import Control.Distributed.Session.Closure (+ SpawnSession (..),+ SessionWrap (..),+ sessionRemoteTable,+ remoteSessionStatic,+ remoteSessionClosure,+ remoteSessionStatic',+ remoteSessionClosure',+ spawnChannelStatic,+ spawnChannelClosure,+ evalLocalSession,+ remoteSpawnSessionStatic,+ remoteSpawnSessionClosure,+ remoteSpawnSessionStatic',+ remoteSpawnSessionClosure',+ rrSpawnSessionSendStatic,+ rrSpawnSessionSendClosure,+ rrSpawnSessionExpectStatic,+ rrSpawnSessionExpectClosure+ )++import Control.Distributed.Session.STChannel (+ Message(..),+ STSendPort(..),+ STReceivePort(..),+ STChan,+ STChanBi,+ UTChan,+ newSTChan,+ newSTChanBi,+ newUTChan,+ toSTChan,+ toSTChanBi,+ sendProxy,+ recvProxy,+ sendSTChan,+ recvSTChan,+ STSplit(..),+ STRec(..),+ STChannelT(..),+ sendSTChanM,+ recvSTChanM,+ sel1ChanM,+ sel2ChanM,+ off1ChanM,+ off2ChanM,+ recChanM,+ wkChanM,+ varChanM,+ epsChanM+ )++import Control.Distributed.Session.Lifted (+ utsend,+ usend,+ expect,+ expectTimeout,+ newChan,+ sendChan,+ receiveChan,+ receiveChanTimeout,+ mergePortsBiased,+ mergePortsRR,+ unsafeSend,+ unsafeSendChan,+ unsafeNSend,+ unsafeNSendRemote,+ receiveWait,+ receiveTimeout,+ unwrapMessage,+ handleMessage,+ handleMessage_,+ handleMessageP,+ handleMessageP_,+ handleMessageIf,+ handleMessageIf_,+ handleMessageIfP,+ handleMessageIfP_,+ forward,+ uforward,+ delegate,+ relay,+ proxy,+ proxyP,+ spawn,+ spawnP,+ call,+ callP,+ terminate,+ die,+ kill,+ exit,+ catchExit,+ catchExitP,+ catchesExit,+ catchesExitP,+ getSelfPid,+ getSelfNode,+ getOthPid,+ getOthNode,+ getProcessInfo,+ getNodeStats,+ link,+ linkNode,+ unlink,+ unlinkNode,+ monitor,+ monitorNode,+ monitorPort,+ unmonitor,+ withMonitor,+ withMonitor_,+ withMonitorP,+ withMonitorP_,+ unStatic,+ unClosure,+ say,+ register,+ unregister,+ whereis,+ nsend,+ registerRemoteAsync,+ reregisterRemoteAsync,+ whereisRemoteAsync,+ nsendRemote,+ spawnAsync,+ spawnAsyncP,+ spawnSupervised,+ spawnSupervisedP,+ spawnLink,+ spawnLinkP,+ spawnMonitor,+ spawnMonitorP,+ spawnChannel,+ spawnChannelP,+ spawnLocal,+ spawnLocalP,+ spawnChannelLocal,+ spawnChannelLocalP,+ callLocal,+ callLocalP,+ reconnect,+ reconnectPort+ )
+ src/Control/Distributed/Session/Closure.hs view
@@ -0,0 +1,239 @@+{-# LANGUAGE DataKinds #-}+{-# LANGUAGE GADTs #-}+-- | We cannot create a `Closure` of a `Session`, because its type parameters are of a different kind than `*`.+--+-- To accomedate for this drawback we define two data types that existentially quantify the type parameters of a `Session`.+--+-- We also define a set of static and closure functions for remotely spawning sessions.+module Control.Distributed.Session.Closure (+ -- * Encapsulation+ SpawnSession (..),+ SessionWrap (..),+ -- * RemoteTable+ sessionRemoteTable,+ -- * Static and Closures+ -- ** Singular+ remoteSessionStatic,+ remoteSessionClosure,+ remoteSessionStatic',+ remoteSessionClosure',+ -- ** SpawnChannel+ spawnChannelStatic,+ spawnChannelClosure,+ -- ** Local Remote Evaluation+ evalLocalSession,+ remoteSpawnSessionStatic,+ remoteSpawnSessionClosure,+ remoteSpawnSessionStatic',+ remoteSpawnSessionClosure',+ -- ** Remote Remote Evaluation+ rrSpawnSessionSendStatic,+ rrSpawnSessionSendClosure,+ rrSpawnSessionExpectStatic,+ rrSpawnSessionExpectClosure+) where++import Control.SessionTypes.Types+import Control.Distributed.Session.Eval+import Control.Distributed.Session.STChannel as ST+import Control.Distributed.Session.Session++import Control.Distributed.Process hiding (spawnChannel)+import Control.Distributed.Process.Closure+import Control.Distributed.Process.Serializable (Serializable)+import Control.Distributed.Static++import Data.ByteString.Lazy (ByteString)+import Data.Binary (encode, decode)+import Data.Rank1Dynamic (toDynamic)+import Data.Rank1Typeable (ANY, Typeable)++-- | Data type that encapsulates two sessions for the purpose of remotely spawning them+-- +-- The session types of the sessions are existentially quantified, but we still ensure duality and constrain them properly, such that they can be passed to `evalSession`.+data SpawnSession a b where+ SpawnSession :: (HasConstraintST Serializable s, HasConstraintST Serializable (DualST s), Typeable a, Typeable b) => + Session ('Cap '[] s) r a -> Session ('Cap '[] (DualST s)) r b -> SpawnSession a b++-- | Data type that encapsulates a single session performing no session typed action that can be remotely spawned.+--+-- We use this data type mostly for convenience in combination with `evalSessionEq` allowing us to avoid the `Serializable` constraint.+data SessionWrap a where+ SessionWrap :: Session s s a -> SessionWrap a++-- | Static function for remotely spawning a single session+-- +-- When remotely spawning any session we must always pass it the `ProcessId` and `NodeId` of the spawning process.+--+-- We must pass a Closure of a `SessionWrap` instead of just a `SessionWrap`, because that would require+-- serializing a `SessionWrap` which is not possible.+--+-- Furthermore, we must also pass a `SerializableDict` that shows how to serialize a value of type `a`.+remoteSessionStatic :: Static (SerializableDict a -> Closure (SessionWrap a) -> Process a)+remoteSessionStatic = staticLabel "$remoteSession"++evalRemoteSession :: SerializableDict a -> Closure (SessionWrap a) -> Process a+evalRemoteSession SerializableDict proc = do+ (SessionWrap sess) <- unClosure proc+ evalSessionEq sess++-- | Closure function for remotely spawning a single session+remoteSessionClosure :: Static (SerializableDict a) -> Closure (SessionWrap a) -> Closure (Process a)+remoteSessionClosure sdict proc = closure decoder (encode proc)+ where decoder = (remoteSessionStatic `staticApply` sdict) `staticCompose` decodeSessionWrap ++-- | Same as `remoteSessionStatic`, except that we do not need to provide a `SerializableDict`.+remoteSessionStatic' :: Static (Closure (SessionWrap ()) -> Process ())+remoteSessionStatic' = staticLabel "$remoteSession'"++evalRemoteSession' :: Closure (SessionWrap ()) -> Process ()+evalRemoteSession' proc = do+ (SessionWrap sess) <- unClosure proc+ evalSessionEq sess++-- | Same as `remoteSessionClosure`, except that we do not need to provide a `SerializableDict`.+remoteSessionClosure' :: Closure (SessionWrap ()) -> Closure (Process ())+remoteSessionClosure' tpl = closure decoder (encode tpl)+ where decoder = remoteSessionStatic' `staticCompose` decodeSessionWrap++-- | A static function specific to the lifted `Control.Distributed.Session.Lifted.spawnChannel` function that can be found in "Control.Distributed.Session.Lifted"+spawnChannelStatic :: Static (SerializableDict a -> Closure (ReceivePort a -> SessionWrap ()) -> ReceivePort a -> Process ())+spawnChannelStatic = staticLabel "$spawnChannel"++spawnChannel :: SerializableDict a -> Closure (ReceivePort a -> SessionWrap ()) -> ReceivePort a -> Process ()+spawnChannel SerializableDict proc rp = do+ (SessionWrap sess) <- unClosure proc >>= \f -> return (f rp)+ evalSessionEq sess++-- | A closure specific to the lifted `spawnChannel` function that can be found in "Control.Distributed.Session.Lifted"+spawnChannelClosure :: Static (SerializableDict a) -> Closure (ReceivePort a -> SessionWrap ()) -> Closure (ReceivePort a -> Process ())+spawnChannelClosure sdict proc = closure decoder (encode proc)+ where decoder = (spawnChannelStatic `staticApply` sdict) `staticCompose` decodeSpawnChannel++-- | Function that evalutes the first argument of a `SpawnSession` in a local manner.+--+-- It is local in that we do not create an accompanying closure.+evalLocalSession :: Typeable a => (ProcessId, NodeId, Closure (SpawnSession a ())) -> Process a+evalLocalSession (pidOth, nodeOth, proc) = do+ (spSelf, rpSelf) <- ST.newUTChan+ send pidOth spSelf + spOth <- expect :: Process (SendPort ST.Message)+ (SpawnSession s r) <- unClosure proc+ evalSession s (SessionInfo pidOth nodeOth (spOth, rpSelf))++-- | Static function for remotely evaluating the second argument of a `SpawnSession`.+--+-- This function works dually to `evalLocalSession`.+remoteSpawnSessionStatic :: Static (SerializableDict a -> (ProcessId, NodeId, Closure (SpawnSession a ())) -> Process ())+remoteSpawnSessionStatic = staticLabel "$remoteSpawnSession"+ +evalRemoteSpawnSession :: SerializableDict a -> (ProcessId, NodeId, Closure (SpawnSession a ())) -> Process () +evalRemoteSpawnSession SerializableDict (pidOth, nodeOth, proc) = do+ (spSelf, rpSelf) <- ST.newUTChan+ send pidOth spSelf + spOth <- expect :: Process (SendPort ST.Message)+ (SpawnSession s r) <- unClosure proc+ evalSession r (SessionInfo pidOth nodeOth (spOth, rpSelf))++-- | Closure for remotely evaluating the second argument of a `SpawnSession`+remoteSpawnSessionClosure :: Static (SerializableDict a) -> (ProcessId, NodeId, Closure (SpawnSession a ())) -> Closure (Process ())+remoteSpawnSessionClosure tdictS tpl = closure decoder (encode tpl)+ where decoder :: Static (ByteString -> Process ())+ decoder = (remoteSpawnSessionStatic `staticApply` tdictS) `staticCompose` decodeSpawnSession++-- | Same as `remoteSpawnSessionStatic`, except for that we do not need to provide a `SerializableDict`.+remoteSpawnSessionStatic' :: Static ((ProcessId, NodeId, Closure (SpawnSession () ())) -> Process ())+remoteSpawnSessionStatic' = staticLabel "$remoteSpawnSession'"++evalRemoteSpawnSession' :: (ProcessId, NodeId, Closure (SpawnSession () ())) -> Process () +evalRemoteSpawnSession' (pidOth, nodeOth, proc) = do+ (spSelf, rpSelf) <- ST.newUTChan+ send pidOth spSelf + spOth <- expect :: Process (SendPort ST.Message)+ (SpawnSession _ r) <- unClosure proc+ evalSession r (SessionInfo pidOth nodeOth (spOth, rpSelf))++-- | Same as `remoteSpawnSessionClosure`, except for that we do not need to provide a `SerializableDict`.+remoteSpawnSessionClosure' :: (ProcessId, NodeId, Closure (SpawnSession () ())) -> Closure (Process ())+remoteSpawnSessionClosure' tpl = closure decoder (encode tpl)+ where decoder :: Static (ByteString -> Process ())+ decoder = remoteSpawnSessionStatic' `staticCompose` decodeSpawnSession++-- | Static function for remotely evaluating the second argument of a `SpawnSession`+-- +-- This function is very similar to `remoteSpawnSessionStatic'`. The difference is that this function assumes that+-- the other session was also remotely spawned. +--+-- Therefore we require an extra send of the `ProcessId` of the to be spawned process.+rrSpawnSessionSendStatic :: Static ((ProcessId, NodeId, Closure (SpawnSession () ())) -> Process ())+rrSpawnSessionSendStatic = staticLabel "$rrSpawnSessionSend"++rrSpawnSessionSend :: (ProcessId, NodeId, Closure (SpawnSession () ())) -> Process ()+rrSpawnSessionSend (pid, node, proc) = do+ pidSelf <- getSelfPid+ (spSelf, rpSelf) <- ST.newUTChan++ send pid pidSelf+ send pid spSelf++ spOth <- expect :: Process (SendPort ST.Message)++ (SpawnSession _ sess) <- unClosure proc+ evalSession sess (SessionInfo pid node (spOth, rpSelf))++-- | Closure for remotely evaluating the second argument of a `SpawnSession`.+rrSpawnSessionSendClosure :: (ProcessId, NodeId, Closure (SpawnSession () ())) -> Closure (Process ())+rrSpawnSessionSendClosure tpl = closure decoder (encode tpl)+ where decoder :: Static (ByteString -> Process ())+ decoder = rrSpawnSessionSendStatic `staticCompose` decodeSpawnSession++-- | Closure for remotely evaluating the first argument of a `SpawnSession`+--+-- This function acts dual to `rrSpawnSessionSend` and assumes that it will first receive a `ProcessId`.+rrSpawnSessionExpectStatic :: Static ((NodeId, Closure (SpawnSession () ())) -> Process ())+rrSpawnSessionExpectStatic = staticLabel "$rrSpawnSessionExpect"++rrSpawnSessionExpect :: (NodeId, Closure (SpawnSession () ())) -> Process ()+rrSpawnSessionExpect (node, proc) = do+ (spSelf, rpSelf) <- ST.newUTChan++ pidOth <- expect+ send pidOth spSelf+ spOth <- expect :: Process (SendPort ST.Message)++ SpawnSession sess _ <- unClosure proc+ evalSession sess (SessionInfo pidOth node (spOth, rpSelf))++-- | Closure for remotely evaluating the first argument of a `SpawnSession`.+rrSpawnSessionExpectClosure :: (NodeId, Closure (SpawnSession () ())) -> Closure (Process ())+rrSpawnSessionExpectClosure tpl = closure decoder (encode tpl)+ where decoder :: Static (ByteString -> Process ())+ decoder = rrSpawnSessionExpectStatic `staticCompose` decodeSpawnSessionNoPid++decodeSpawnSession :: Static (ByteString -> (ProcessId, NodeId, Closure (SpawnSession a ())))+decodeSpawnSession = staticLabel "$decodeSpawnSession"++decodeSpawnSessionNoPid :: Static (ByteString -> (NodeId, Closure (SpawnSession a ())))+decodeSpawnSessionNoPid = staticLabel "$decodeSpawnSessionNoPid"++decodeSessionWrap :: Static (ByteString -> Closure (SessionWrap a))+decodeSessionWrap = staticLabel "$decodeSessionWrap"++decodeSpawnChannel :: Static (ByteString -> Closure (ReceivePort a -> SessionWrap ()))+decodeSpawnChannel = staticLabel "$decodeSpawnChannel"++-- | RemoteTable that binds all in this module defined static functions to their corresponding evaluation functions.+sessionRemoteTable :: RemoteTable -> RemoteTable+sessionRemoteTable rtable =+ registerStatic "$remoteSession" (toDynamic (evalRemoteSession :: SerializableDict ANY -> Closure (SessionWrap ANY) -> Process ANY)) $+ registerStatic "$remoteSession'" (toDynamic evalRemoteSession') $+ registerStatic "$spawnChannel" (toDynamic (spawnChannel :: SerializableDict ANY -> Closure (ReceivePort ANY -> SessionWrap ()) -> ReceivePort ANY -> Process ())) $+ registerStatic "$remoteSpawnSession" (toDynamic (evalRemoteSpawnSession :: SerializableDict ANY -> (ProcessId, NodeId, Closure (SpawnSession ANY ())) -> Process ())) $+ registerStatic "$remoteSpawnSession'" (toDynamic evalRemoteSpawnSession') $+ registerStatic "$rrSpawnSessionSend" (toDynamic rrSpawnSessionSend) $+ registerStatic "$rrSpawnSessionExpect" (toDynamic rrSpawnSessionExpect) $+ registerStatic "$decodeSpawnSession" (toDynamic (decode :: ByteString -> (ProcessId, NodeId, Closure (SpawnSession ANY ())))) $+ registerStatic "$decodeSpawnSessionNoPid" (toDynamic (decode :: ByteString -> (NodeId, Closure (SpawnSession ANY ())))) $+ registerStatic "$decodeSessionWrap" (toDynamic (decode :: ByteString -> Closure (SessionWrap ANY))) $+ registerStatic "$decodeSpawnChannel" (toDynamic (decode :: ByteString -> Closure (ReceivePort ANY -> SessionWrap ()))) $+ rtable
+ src/Control/Distributed/Session/Debug.hs view
@@ -0,0 +1,103 @@+{-# LANGUAGE DataKinds #-}+{-# LANGUAGE RebindableSyntax #-}+-- | This module describes an interpreter for purely evaluating session typed programs+--+-- that is based on the paper /Beauty in the beast/ by /Swierstra, W., & Altenkirch, T./+--+-- Impurity in a session typed programs mainly comes from three things: receives, branching and lifting.+--+-- * Using the session type we can easily determine the type of the message that each receive should expect.+-- This information allows us to define a stream of values of different types that provides input for each receive.+--+-- * When evaluating a session we send and receive integers to choose a branch in a selection and offering respectively.+-- If we want to purely evaluate a session typed program, then we must provide some kind of input that makes this choice for us.+-- * The current structure of the `Lift` constructor does not allow us to purely evaluate a `Lift`.+-- As such a session typed program may not contain a lift for it to be purely evaluated. See `runM` as an alternative.+module Control.Distributed.Session.Debug (+ -- * Pure+ run,+ runAll,+ runSingle,+ runP,+ runAllP,+ runSingleP,+ runM,+ runAllM,+ runSingleM,+ -- * Input+ D.Stream(..),+ -- * Output+ D.Output(..),+)+where++import Control.SessionTypes+import Control.SessionTypes.Indexed+import qualified Control.SessionTypes.Debug as D+import Control.Distributed.Session.Session+import Control.Distributed.Process+++-- | Purely evaluates a given `Session` using the input defined by `Stream`.+-- +-- The output is described in terms of the session type actions within the given program+--+-- An example of how to use this function goes as follows:+--+-- @+-- prog :: Session ('Cap '[] (Int :!> String :?> Eps)) ('Cap '[] Eps) String+-- prog = send 5 >> recv >>= eps+--+-- strm = S_Send $ S_Recv "foo" S_Eps+-- @+--+-- >>> run prog strm+-- O_Send 5 $ O_Recv "foo" $ O_Eps "foo"+run :: HasConstraint Show s => Session s ('Cap ctx Eps) a -> D.Stream s -> D.Output s a+run sess strm = D.run (runSession sess Nothing) strm++-- | Instead of describing the session typed actions, it returns a list of the results+-- of all branches of all offerings.+--+-- @+-- prog = offer (eps 10) (eps 5)+-- strm = S_OffS S_Eps S_Eps+-- @+--+-- >>> runAll prog strm+-- [10,5]+runAll :: HasConstraint Show s => Session s ('Cap ctx Eps) a -> D.Stream s -> [a]+runAll sess strm = D.runAll (runSession sess Nothing) strm++-- | Same as `runAll` but applies `head` to the resulting list+--+-- >>> runSingle prog strm+-- 10+runSingle :: HasConstraint Show s => Session s ('Cap ctx Eps) a -> D.Stream s -> a+runSingle sess strm = D.runSingle (runSession sess Nothing) strm++-- | `run` cannot deal with lifted computations. This makes it limited to session typed programs without any use of lift.+--+-- This function allows us to evaluate lifted computations, but as a consequence is no longer entirely pure.+runP :: HasConstraint Show s => Session s ('Cap ctx Eps) a -> SessionInfo -> D.Stream s -> Process (D.Output s a)+runP sess si strm = D.runM (runSession sess $ Just si) strm++-- | Monadic version of `runAll`.+runAllP :: HasConstraint Show s => Session s ('Cap ctx Eps) a -> SessionInfo -> D.Stream s -> Process [a]+runAllP sess si strm = D.runAllM (runSession sess $ Just si) strm++-- | Monad version of `runSingle`+runSingleP :: HasConstraint Show s => Session s ('Cap ctx Eps) a -> SessionInfo -> D.Stream s -> Process a+runSingleP sess si strm = D.runSingleM (runSession sess $ Just si) strm++-- | Session typed version of `runP`+runM :: HasConstraint Show s => Session s ('Cap ctx Eps) a -> D.Stream s -> Session r r (D.Output s a)+runM sess strm = ask >>= \si -> liftP $ D.runM (runSession sess si) strm++-- | Session typed version of `runAllP`+runAllM :: HasConstraint Show s => Session s ('Cap ctx Eps) a -> D.Stream s -> Session r r [a]+runAllM sess strm = ask >>= \si -> liftP $ D.runAllM (runSession sess si) strm++-- | Session typed version of `runSingleP`+runSingleM :: HasConstraint Show s => Session s ('Cap ctx Eps) a -> D.Stream s -> Session r r a+runSingleM sess strm = ask >>= \si -> liftP $ D.runSingleM (runSession sess si) strm
+ src/Control/Distributed/Session/Eval.hs view
@@ -0,0 +1,159 @@+{-# LANGUAGE RebindableSyntax #-}+{-# LANGUAGE TypeOperators #-}+{-# LANGUAGE DataKinds #-}+{-# LANGUAGE TypeFamilies #-}+{-# LANGUAGE ScopedTypeVariables #-}+-- | This module defines two interpreters for mapping the Cloud Haskell semantics to the constructors of `STTerm`.+module Control.Distributed.Session.Eval (+ evalSession,+ evalSessionEq,+ evalSessionEq'+) where++import Control.SessionTypes+import Control.SessionTypes.Indexed+import Control.SessionTypes.Types+import Control.Distributed.Session.STChannel+import Control.Distributed.Session.Session++import qualified Control.Distributed.Process as P+import Control.Distributed.Process.Serializable+import Data.Proxy (Proxy(..))++import qualified Prelude as PL++-- Some type synonyms for the send and receive ports used in this module+type SendPortST s = RemoveRecv (SendInsInt s)+type RecvPortST s = RemoveSend (RecvInsInt s)+type MapRecvPortST xs = MapRemoveSend (MapRecvInsInt xs)++-- | This function unpacks a `Session` to a `STTerm` using a given `SessionInfo`. +--+-- It then evaluates the `STTerm` by mapping Cloud Haskell semantics to each constructor of `STTerm`.+--+-- The function relies on that there exists another session (on a different process) that is also being evaluated (using evalSession)+-- and acts as the dual the session that function is now evaluating.+--+-- The underlying communication method is a session typed channel (`STChannelT`). There should be no interference from other processes, unless+-- you go through the effort of sharing the send port.+evalSession :: forall s r a. HasConstraint Serializable s => Session s r a -> SessionInfo -> P.Process a+evalSession sess si =+ let st = runSession sess (Just si)+ (sp', rp') = toSTChanBi (utchan si) (Proxy :: Proxy (SendInsInt s)) (Proxy :: Proxy (RecvInsInt s))+ in PL.fmap fst $ runSTChannelT (eval st) (sp', rp')++eval :: HasConstraint Serializable s => STTerm P.Process s r a -> + STChannelT P.Process (SendPortST s :*: RecvPortST s) + (SendPortST r :*: RecvPortST r) + a+eval (Send a r) = do+ sendSTChanM a+ eval r+eval (Recv r) = do+ a <- recvSTChanM+ eval (r a)+eval s@(Sel1 _) = unFoldSelect 0 s+eval s@(Sel2 _) = unFoldSelect 0 s+eval o@(OffS _ _) = do+ x <- recvSTChanM+ unFoldOffer x o+eval o@(OffZ _) = do+ x <- recvSTChanM+ unFoldOffer x o+eval (Rec s) = do+ recChanM+ eval s+eval (Weaken s) = do+ wkChanM+ eval s+eval (Var s) = do+ varChanM+ eval s+eval (Lift m) = do+ st <- lift m+ eval st+eval (Ret a) = do+ return a++-- | Similar to `evalSession`, except for that it does not evaluate session typed actions.+--+-- Only returns and lifted computations are evaluated. This also means that there does not need to be a+-- dual session that is evaluated on a different process.+--+-- It also assumes that `SessionInfo` is not used. Use `evalSessionEq'` if this is not the case.+evalSessionEq :: Session s s a -> P.Process a+evalSessionEq sess = do+ let st = runSession sess Nothing+ evalST st+ where+ evalST :: STTerm P.Process s s a -> P.Process a+ evalST (Ret a) = PL.return a+ evalST (Lift m) = m PL.>>= evalST++-- | Same as `evalSessionEq`, but you may now provide a `SessionInfo`.+evalSessionEq' :: Session s s a -> SessionInfo -> P.Process a+evalSessionEq' sess si = do+ let st = runSession sess (Just si)+ evalST st+ where+ evalST :: STTerm P.Process s s a -> P.Process a+ evalST (Ret a) = PL.return a+ evalST (Lift m) = m PL.>>= evalST++unFoldSelect :: (s ~ 'Cap ctx (Sel xs), HasConstraint Serializable s) => + Int -> STTerm P.Process s r a -> + STChannelT P.Process (SendPortST s :*: RecvPortST s) + (SendPortST r :*: RecvPortST r) + a+unFoldSelect k (Sel1 s) = sel1ChanM >> sendSTChanM k >> eval s+unFoldSelect k (Sel2 s) = sel2ChanM >> unFoldSelect (k + 1) s++unFoldOffer :: (s ~ 'Cap ctx (Off xs), HasConstraint Serializable s) => Int -> STTerm P.Process s r a -> + STChannelT P.Process (SendPortST s :*: 'Cap (MapRecvPortST ctx) (Off (MapRecvPortST xs))) + (SendPortST r :*: RecvPortST r) + a+unFoldOffer _ (OffZ s) = off1ChanM >> eval s+unFoldOffer 0 (OffS s _) = off1ChanM >> eval s+unFoldOffer n (OffS _ xs) = off2ChanM >> unFoldOffer (n - 1) xs++type family MapSendInsInt ss where+ MapSendInsInt '[] = '[]+ MapSendInsInt (s ': xs) = (Int :!> SendInsIntST s) ': MapSendInsInt xs++type family MapSendInsInt' ss where+ MapSendInsInt' '[] = '[]+ MapSendInsInt' (s ': xs) = SendInsIntST s ': MapSendInsInt' xs++type family SendInsInt c where+ SendInsInt ('Cap ctx s) = 'Cap (MapSendInsInt' ctx) (SendInsIntST s)++type family SendInsIntCtx ctx where+ SendInsIntCtx '[] = '[]+ SendInsIntCtx (s ': ctx) = SendInsIntST s ': SendInsIntCtx ctx++type family SendInsIntST s where+ SendInsIntST (a :!> r) = a :!> (SendInsIntST r)+ SendInsIntST (a :?> r) = a :?> SendInsIntST r+ SendInsIntST (Sel xs) = Sel (MapSendInsInt xs)+ SendInsIntST (Off xs) = Off (MapSendInsInt' xs)+ SendInsIntST (R s) = R (SendInsIntST s)+ SendInsIntST (Wk s) = Wk (SendInsIntST s)+ SendInsIntST V = V+ SendInsIntST Eps = Eps++type family MapRecvInsInt ss where+ MapRecvInsInt '[] = '[]+ MapRecvInsInt (s ': xs) = RecvInsIntST s ': MapRecvInsInt xs++type family RecvInsInt c where+ RecvInsInt ('Cap ctx s) = 'Cap (MapRecvInsInt ctx) (RecvInsIntST s)++type family RecvInsIntST s where+ RecvInsIntST (a :!> r) = a :!> RecvInsIntST r+ RecvInsIntST (a :?> r) = a :?> RecvInsIntST r+ RecvInsIntST (Sel xs) = Sel (MapRecvInsInt xs)+ RecvInsIntST (Off xs) = Int :?> (Off (MapRecvInsInt xs)) + RecvInsIntST (R s) = R (RecvInsIntST s)+ RecvInsIntST (Wk s) = Wk (RecvInsIntST s)+ RecvInsIntST V = V+ RecvInsIntST Eps = Eps
+ src/Control/Distributed/Session/Exception.hs view
@@ -0,0 +1,43 @@+{-# LANGUAGE MultiParamTypeClasses #-}+{-# LANGUAGE PolyKinds #-}+{-# LANGUAGE FlexibleInstances #-}+-- | Provides instances for `Session` of `IxMonadThrow`, `IxMonadCatch` and `IxMonadMask`.+--+-- These instances should behave no differently from the corresponding `MonadThrow`, `MonadCatch` and `MonadMask` instances for `Process`.+-- For more documentation please visit "Control.Monad.Catch"+--+-- The reason that the instances are placed in a separate module is to avoid a circular dependency of the modules.+-- +-- The instances require evaluation of the sessions, therefore "Control.Distributed.Session.Eval" should be imported.+--+-- However that module imports "Control.Distributed.Session.Session". Placing these instances in this module would then require importing "Control.Distributed.Session.Eval" causing a circular dependency.+--+-- Note that these instances are already exported by "Control.Distributed.Session", such that this module should need no explicit import.+module Control.Distributed.Session.Exception where++import qualified Control.SessionTypes.Indexed as I+import Control.Monad.Catch as C+import Control.SessionTypes.Indexed+import Control.SessionTypes.Codensity (rep)+import Control.Distributed.Session.Session+import Control.Distributed.Session.Eval (evalSessionEq)+import Control.Distributed.Process++instance IxMonadThrow Session s where+ throwM e = Session $ \_ -> rep $ lift $ C.throwM e++instance IxMonadCatch Session s where+ catch sess h = Session $ \si ->+ let p = evalSessionEq sess+ in rep $ lift $ C.catch p (\e -> evalSessionEq (h e))++instance IxMonadMask Session s where+ mask s = Session $ \si ->+ rep $ lift $ C.mask $ \restore -> evalSessionEq (s $ liftRestore restore)+ where liftRestore :: (Process a -> Process a) -> Session s s a -> Session s s a+ liftRestore restore = \s -> Session $ \si -> rep $ lift $ restore $ evalSessionEq s+ + uninterruptibleMask s = Session $ \si ->+ rep $ lift $ C.uninterruptibleMask $ \restore -> evalSessionEq (s $ liftRestore restore)+ where liftRestore :: (Process a -> Process a) -> Session s s a -> Session s s a+ liftRestore restore = \s -> Session $ \si -> rep $ lift $ restore $ evalSessionEq s
+ src/Control/Distributed/Session/Interactive.hs view
@@ -0,0 +1,57 @@+{-# LANGUAGE DataKinds #-}+-- | This module exposes two functions for interactively evaluation a session typed program+--+-- To run a session you must have two participating actors. In our context, the actors are session typed programs.+-- +-- Using this module the user will act as one of the actors in the session by suppling values to a receive+--+-- and selecting a branch for offerings.+module Control.Distributed.Session.Interactive (+ interactive,+ interactiveStep+) where++import qualified Control.SessionTypes.Interactive as S+import Control.SessionTypes.Types+import Control.Distributed.Session.STChannel (newUTChan)+import Control.Distributed.Session.Session++import Data.Typeable (Typeable)+import Control.Distributed.Process (Process, getSelfPid, getSelfNode)++-- | For this function the user will act as the dual to the given session. User interaction is only required+-- when the given program does a receive or an offer.+--+-- A possible interaction goes as follows:+--+-- @+-- prog = do+-- send 5+-- x <- recv+-- offer (eps x) (eps "")+--+-- main = interactive prog+-- @+-- +-- >> Enter value of type String: "test"+-- >> (L)eft or (R)ight: L+-- > "test"+interactive :: (HasConstraints '[Read, Show, Typeable] s, Show a) => Session s r a -> Process a+interactive sess = do+ pid <- getSelfPid+ node <- getSelfNode + utchan <- newUTChan++ S.interactive $ runSession sess Nothing++-- | Different from `interactive` is that this function gives the user the choice to abort the session+-- after each session typed action. +--+-- Furthermore, it also prints additional output describing which session typed action occurred.+interactiveStep :: (HasConstraints '[Read, Show, Typeable] s, Show a) => Session s r a -> Process (Maybe a)+interactiveStep sess = do+ pid <- getSelfPid+ node <- getSelfNode+ utchan <- newUTChan+ + S.interactiveStep $ runSession sess Nothing
+ src/Control/Distributed/Session/Lifted.hs view
@@ -0,0 +1,481 @@+{-# LANGUAGE RebindableSyntax #-}+-- | In this module we lift all functions in "Control.Distributed.Process" that return a function of type Process a to Session s s a.+--+-- Since the functions in this module work identical to the ones in "Control.Distributed.Process" we will refer to that module for documentation.+--+-- There is however some explanation required for functions that take a `Process` as an argument.+--+-- For the functions that also take a Process a as an argument we derive two functions. One that still takes a Process a and one that takes a Session s s a.+--+-- There are also functions that take a Closure (Process ()) as an argument. We cannot lift this to be Closure (Session s s ()) as is explained in "Control.Distributed.Session.Closure".+--+-- To accomodate for this drawback we instead have these functions take a Closure (SessionWrap ()) as an argument.+--+-- Here is an example on how to call `call`.+--+-- @+--+-- {-\# LANGUAGE TemplateHaskell \#-}+-- import qualified SessionTypes.Indexed as I+-- import Control.Distributed.Session (SessionWrap(..), sessionRemoteTable, call, evalSessionEq)+-- import Control.Distributed.Process (liftIO, Process, RemoteTable, NodeId)+-- import Control.Distributed.Process.Serializable (SerializableDict(..))+-- import Control.Distributed.Process.Closure (remotable, mkStaticClosure, mkStatic)+-- import Control.Distributed.Process.Node+-- import Network.Transport.TCP+--+-- sessWrap :: SessionWrap Int+-- sessWrap = SessionWrap $ I.return 5+--+-- sdictInt :: SerializableDict Int+-- sdictInt = SerializableDict+--+-- remotable ['sdictInt, 'sessWrap]+--+-- p1 :: NodeId -> Process ()+-- p1 nid = do+-- a <- evalSessionEq (call $(mkStatic 'sdictInt) nid $(mkStaticClosure 'sessWrap))+-- liftIO $ putStrLn $ show a+--+-- myRemoteTable :: RemoteTable+-- myRemoteTable = Main.__remoteTable $ sessionRemoteTable initRemoteTable+--+-- main :: IO ()+-- main = do+-- Right t <- createTransport "127.0.0.1" "100000" defaultTCPParameters+-- node <- newLocalNode t myRemoteTable+-- runProcess node $ p1 (localNodeId node)+--+-- @+--+-- >>> main+-- > 5+-- +-- In p1 we run a session that makes a call and then prints out the result of that call.+--+-- Note that this is the call function from "SessionTyped.Distributed.Process.Lifted". It takes a Static (SerializableDict a) and a Closure (SessionWrap a).+--+-- To create a static serializable dictionary we first have to define a function that returns a monomorphic serializable dictionary.+--+-- > sdictInt :: SerializableDict Int+-- > sdictInt = SerializableDict+--+-- We then pass 'sdictInt to remoteable, which is a top-level Template Haskell splice.+--+-- > remoteable ['sdictInt]+--+-- Now we can create a static serializable dictionary with +--+-- > $(mkStatic 'sdictInt)+--+-- To create a closure for a Session s s we have to wrap it in a `SessionWrap`.+--+-- > sessWrap :: SessionWrap Int+-- > sessWrap = SessionWrap $ I.return 5+-- +-- Similarly to sdictInt this needs to be a top level definition such that we can use Template Haskell to derive a Closure +--+-- > remotable ['sdictInt, 'sessWrap]+-- > $(mkStaticClosure 'sessWrap)+--+-- Since `call` makes use of internally defined closures, you also have to include `sessionRemoteTable`. +--+-- > myRemoteTable = Main.__remoteTable $ sessionRemoteTable initRemoteTable+--+-- The remote tables contains a mapping from labels to evaluation functions that a node uses to evaluate closures.+-- +-- > node <- newLocalNode t myRemoteTable+-- +-- +module Control.Distributed.Session.Lifted (+ utsend,+ usend,+ expect,+ expectTimeout,+ newChan,+ sendChan,+ receiveChan,+ receiveChanTimeout,+ mergePortsBiased,+ mergePortsRR,+ unsafeSend,+ unsafeSendChan,+ unsafeNSend,+ unsafeNSendRemote,+ receiveWait,+ receiveTimeout,+ unwrapMessage,+ handleMessage,+ handleMessage_,+ handleMessageP,+ handleMessageP_,+ handleMessageIf,+ handleMessageIf_,+ handleMessageIfP,+ handleMessageIfP_,+ forward,+ uforward,+ delegate,+ relay,+ proxy,+ proxyP,+ spawn,+ spawnP,+ call,+ callP,+ terminate,+ die,+ kill,+ exit,+ catchExit,+ catchExitP,+ catchesExit,+ catchesExitP,+ getSelfPid,+ getSelfNode,+ getOthPid,+ getOthNode,+ getProcessInfo,+ getNodeStats,+ link,+ linkNode,+ unlink,+ unlinkNode,+ monitor,+ monitorNode,+ monitorPort,+ unmonitor,+ withMonitor,+ withMonitor_,+ withMonitorP,+ withMonitorP_,+ unStatic,+ unClosure,+ say,+ register,+ unregister,+ whereis,+ nsend,+ registerRemoteAsync,+ reregisterRemoteAsync,+ whereisRemoteAsync,+ nsendRemote,+ spawnAsync,+ spawnAsyncP,+ spawnSupervised,+ spawnSupervisedP,+ spawnLink,+ spawnLinkP,+ spawnMonitor,+ spawnMonitorP,+ spawnChannel,+ spawnChannelP,+ spawnLocal,+ spawnLocalP,+ spawnChannelLocal,+ spawnChannelLocalP,+ callLocal,+ callLocalP,+ reconnect,+ reconnectPort+) where++import qualified Control.Distributed.Process as P+import Control.Distributed.Process.Serializable+import Control.Distributed.Session.Session+import Control.Distributed.Session.Closure+import Control.Distributed.Session.Eval+import Control.SessionTypes.Indexed+import Data.Typeable (Typeable)+import qualified Prelude as PL++-- | Unsession typed send+utsend :: Serializable a => P.ProcessId -> a -> Session s s ()+utsend pid a = liftP $ P.send pid a++-- | Unsafe send+usend :: Serializable a => P.ProcessId -> a -> Session s s ()+usend pid a = liftP $ P.usend pid a++expect :: Serializable a => Session s s a+expect = liftP P.expect++expectTimeout :: Serializable a => Int -> Session s s (Maybe a)+expectTimeout = liftP . P.expectTimeout++newChan :: Serializable a => Session s s (P.SendPort a, P.ReceivePort a)+newChan = liftP P.newChan++sendChan :: Serializable a => P.SendPort a -> a -> Session s s ()+sendChan sp a = liftP $ P.sendChan sp a++receiveChan :: Serializable a => P.ReceivePort a -> Session s s a+receiveChan = liftP . P.receiveChan++receiveChanTimeout :: Serializable a => Int -> P.ReceivePort a -> Session s s (Maybe a)+receiveChanTimeout n rp = liftP $ P.receiveChanTimeout n rp++mergePortsBiased :: Serializable a => [P.ReceivePort a] -> Session s s (P.ReceivePort a)+mergePortsBiased = liftP . P.mergePortsBiased++mergePortsRR :: Serializable a => [P.ReceivePort a] -> Session s s (P.ReceivePort a)+mergePortsRR = liftP . P.mergePortsRR++unsafeSend :: Serializable a => P.ProcessId -> a -> Session s s ()+unsafeSend pid a = liftP $ P.unsafeSend pid a++unsafeUSend :: Serializable a => P.ProcessId -> a -> Session s s ()+unsafeUSend pid a = liftP $ P.unsafeUSend pid a++unsafeSendChan :: Serializable a => P.SendPort a -> a -> Session s s ()+unsafeSendChan pid a = liftP $ P.unsafeSendChan pid a++unsafeNSend :: Serializable a => String -> a -> Session s s ()+unsafeNSend s a = liftP $ P.unsafeNSend s a++unsafeNSendRemote :: Serializable a => P.NodeId -> String -> a -> Session s s ()+unsafeNSendRemote n s a = liftP $ P.unsafeNSendRemote n s a++receiveWait :: [P.Match b] -> Session s s b+receiveWait = liftP . P.receiveWait++receiveTimeout :: Int -> [P.Match b] -> Session s s (Maybe b)+receiveTimeout n ms = liftP $ P.receiveTimeout n ms++unwrapMessage :: Serializable a => P.Message -> Session s s (Maybe a)+unwrapMessage = liftP . P.unwrapMessage++handleMessage :: Serializable a => P.Message -> (a -> Session s s b) -> Session r r (Maybe b)+handleMessage m f = handleMessageP m $ \a -> evalSessionEq (f a)++handleMessageP :: Serializable a => P.Message -> (a -> P.Process b) -> Session s s (Maybe b)+handleMessageP m f = liftP $ P.handleMessage m f++handleMessageIf :: Serializable a => P.Message -> (a -> Bool) -> (a -> Session s s b) -> Session r r (Maybe b)+handleMessageIf m f g = handleMessageIfP m f $ \a -> evalSessionEq (g a)++handleMessageIfP :: Serializable a => P.Message -> (a -> Bool) -> (a -> P.Process b) -> Session s s (Maybe b)+handleMessageIfP m f g = liftP $ P.handleMessageIf m f g++handleMessage_ :: Serializable a => P.Message -> (a -> Session s s ()) -> Session r r ()+handleMessage_ m f = handleMessageP_ m $ \a -> evalSessionEq (f a)++handleMessageP_ :: Serializable a => P.Message -> (a -> P.Process ()) -> Session s s ()+handleMessageP_ m f = liftP $ P.handleMessage_ m f++handleMessageIf_ :: Serializable a => P.Message -> (a -> Bool) -> (a -> Session s s ()) -> Session r r ()+handleMessageIf_ m f g = handleMessageIfP_ m f (\a -> evalSessionEq (g a))++handleMessageIfP_ :: Serializable a => P.Message -> (a -> Bool) -> (a -> P.Process ()) -> Session s s ()+handleMessageIfP_ m f g = liftP $ P.handleMessageIf_ m f g++forward :: P.Message -> P.ProcessId -> Session s s ()+forward m pid = liftP $ P.forward m pid++uforward :: P.Message -> P.ProcessId -> Session s s ()+uforward m pid = liftP $ P.uforward m pid++delegate :: P.ProcessId -> (P.Message -> Bool) -> Session s s ()+delegate pid f = liftP $ P.delegate pid f++relay :: P.ProcessId -> Session s s ()+relay = liftP . P.relay++proxy :: Serializable a => P.ProcessId -> (a -> Session s s Bool) -> Session r r ()+proxy pid f = proxyP pid $ \a -> evalSessionEq (f a)++proxyP :: Serializable a => P.ProcessId -> (a -> P.Process Bool) -> Session s s ()+proxyP pid f = liftP $ P.proxy pid f++spawn :: P.NodeId -> P.Closure (SessionWrap ()) -> Session s s P.ProcessId+spawn n proc = do+ spawnP n $ remoteSessionClosure' proc++spawnP :: P.NodeId -> P.Closure (P.Process ()) -> Session s s P.ProcessId+spawnP n proc = liftP $ P.spawn n proc++call :: Serializable a => P.Static (SerializableDict a) -> P.NodeId -> P.Closure (SessionWrap a) -> Session r r a+call dict n proc = callP dict n $ remoteSessionClosure dict proc++callP :: Serializable a => P.Static (SerializableDict a) -> P.NodeId -> P.Closure (P.Process a) -> Session s s a+callP dict n proc = liftP $ P.call dict n proc++terminate :: Session s s a+terminate = liftP P.terminate++die :: Serializable a => a -> Session s s b+die = liftP . P.die++kill :: P.ProcessId -> String -> Session s s ()+kill pid s = liftP $ P.kill pid s++exit :: Serializable a => P.ProcessId -> a -> Session s s ()+exit pid a = liftP $ P.exit pid a++catchExit :: (Show a, Serializable a) => Session s s b -> (P.ProcessId -> a -> Session r r b) -> Session t t b+catchExit sess f = do+ let prod = evalSessionEq sess+ let pf = \pid a -> evalSessionEq (f pid a)+ catchExitP prod pf++catchExitP :: (Show a, Serializable a) => P.Process b -> (P.ProcessId -> a -> P.Process b) -> Session s s b+catchExitP p f = liftP $ P.catchExit p f++catchesExit :: Session s s b -> [P.ProcessId -> P.Message -> Session r r (Maybe b)] -> Session t t b+catchesExit sess xs = do+ let prod = evalSessionEq sess+ let xsp = map (\f -> \pid m -> evalSessionEq (f pid m)) xs+ catchesExitP prod xsp ++catchesExitP :: P.Process b -> [P.ProcessId -> P.Message -> P.Process (Maybe b)] -> Session s s b+catchesExitP p xs = liftP $ P.catchesExit p xs++getSelfPid :: Session s s P.ProcessId+getSelfPid = liftP P.getSelfPid++getSelfNode :: Session s s P.NodeId+getSelfNode = liftP P.getSelfNode++getOthPid :: Session s s (Maybe P.ProcessId)+getOthPid = Session $ \si -> return $ PL.fmap othPid si++getOthNode :: Session s s (Maybe P.NodeId)+getOthNode = Session $ \si -> return $ PL.fmap othNode si++getProcessInfo :: P.ProcessId -> Session s s (Maybe P.ProcessInfo)+getProcessInfo = liftP . P.getProcessInfo++getNodeStats :: P.NodeId -> Session s s (Either P.DiedReason P.NodeStats)+getNodeStats = liftP . P.getNodeStats++link :: P.ProcessId -> Session s s ()+link = liftP . P.link++linkNode :: P.NodeId -> Session s s ()+linkNode = liftP . P.linkNode++linkPort :: P.SendPort a -> Session s s ()+linkPort = liftP . P.linkPort++unlink :: P.ProcessId -> Session s s ()+unlink = liftP . P.unlink++unlinkNode :: P.NodeId -> Session s s ()+unlinkNode = liftP . P.unlinkNode++unlinkPort :: P.SendPort a -> Session s s ()+unlinkPort = liftP . P.unlinkPort++monitor :: P.ProcessId -> Session s s P.MonitorRef+monitor = liftP . P.monitor++monitorNode :: P.NodeId -> Session s s P.MonitorRef+monitorNode = liftP . P.monitorNode++monitorPort :: Serializable a => P.SendPort a -> Session s s P.MonitorRef+monitorPort = liftP . P.monitorPort++unmonitor :: P.MonitorRef -> Session s s ()+unmonitor = liftP . P.unmonitor++withMonitor :: P.ProcessId -> (P.MonitorRef -> Session s s a) -> Session r r a+withMonitor pid f = withMonitorP pid $ \ref -> evalSessionEq (f ref)++withMonitorP :: P.ProcessId -> (P.MonitorRef -> P.Process a) -> Session s s a+withMonitorP pid f = liftP $ P.withMonitor pid f++withMonitor_ :: P.ProcessId -> Session s s a -> Session r r a+withMonitor_ pid sess = withMonitorP_ pid $ evalSessionEq sess++withMonitorP_ :: P.ProcessId -> P.Process a -> Session s s a+withMonitorP_ pid p = liftP $ P.withMonitor_ pid p++unStatic :: Typeable a => P.Static a -> Session s s a+unStatic = liftP . P.unStatic++unClosure :: Typeable a => P.Closure a -> Session s s a+unClosure = liftP . P.unClosure++say :: String -> Session s s ()+say = liftP . P.say++register :: String -> P.ProcessId -> Session s s ()+register s pid = liftP $ P.register s pid++unregister :: String -> Session s s ()+unregister = liftP . P.unregister++whereis :: String -> Session s s (Maybe P.ProcessId)+whereis = liftP . P.whereis++nsend :: Serializable a => String -> a -> Session s s ()+nsend s a = liftP $ P.nsend s a++registerRemoteAsync :: P.NodeId -> String -> P.ProcessId -> Session s s ()+registerRemoteAsync node s pid = liftP $ P.registerRemoteAsync node s pid++reregisterRemoteAsync :: P.NodeId -> String -> P.ProcessId -> Session s s ()+reregisterRemoteAsync node s pid = liftP $ P.reregisterRemoteAsync node s pid++unregisterRemoteAsync :: P.NodeId -> String -> Session s s ()+unregisterRemoteAsync node s = liftP $ P.unregisterRemoteAsync node s++whereisRemoteAsync :: P.NodeId -> String -> Session s s ()+whereisRemoteAsync node s = liftP $ P.whereisRemoteAsync node s++nsendRemote :: Serializable a => P.NodeId -> String -> a -> Session s s ()+nsendRemote node s a = liftP $ P.nsendRemote node s a++spawnAsync :: P.NodeId -> P.Closure (SessionWrap ()) -> Session r r P.SpawnRef+spawnAsync n proc = spawnAsyncP n $ remoteSessionClosure' proc++spawnAsyncP :: P.NodeId -> P.Closure (P.Process ()) -> Session s s P.SpawnRef+spawnAsyncP n proc = liftP $ P.spawnAsync n proc++spawnSupervised :: P.NodeId -> P.Closure (SessionWrap ()) -> Session s s (P.ProcessId, P.MonitorRef)+spawnSupervised n proc = spawnSupervisedP n $ remoteSessionClosure' proc++spawnSupervisedP :: P.NodeId -> P.Closure (P.Process ()) -> Session s s (P.ProcessId, P.MonitorRef)+spawnSupervisedP n proc = liftP $ P.spawnSupervised n proc++spawnLink :: P.NodeId -> P.Closure (SessionWrap ()) -> Session s s P.ProcessId+spawnLink n proc = spawnLinkP n $ remoteSessionClosure' proc++spawnLinkP :: P.NodeId -> P.Closure (P.Process ()) -> Session s s P.ProcessId+spawnLinkP n proc = liftP $ P.spawnLink n proc++spawnMonitor :: P.NodeId -> P.Closure (SessionWrap ()) -> Session s s (P.ProcessId, P.MonitorRef)+spawnMonitor n proc = spawnMonitorP n $ remoteSessionClosure' proc++spawnMonitorP :: P.NodeId -> P.Closure (P.Process ()) -> Session s s (P.ProcessId, P.MonitorRef)+spawnMonitorP n proc = liftP $ P.spawnMonitor n proc++spawnChannel :: Serializable a => P.Static (SerializableDict a) -> P.NodeId -> P.Closure (P.ReceivePort a -> SessionWrap ()) -> Session s s (P.SendPort a)+spawnChannel st n proc = spawnChannelP st n $ spawnChannelClosure st proc++spawnChannelP :: Serializable a => P.Static (SerializableDict a) -> P.NodeId -> P.Closure (P.ReceivePort a -> P.Process ()) -> Session s s (P.SendPort a)+spawnChannelP st n proc = liftP $ P.spawnChannel st n proc++spawnLocal :: Session s s () -> Session r r P.ProcessId+spawnLocal sess = spawnLocalP $ evalSessionEq sess++spawnLocalP :: P.Process () -> Session s s P.ProcessId+spawnLocalP = liftP . P.spawnLocal++spawnChannelLocal :: Serializable a => (P.ReceivePort a -> Session s s ()) -> Session r r (P.SendPort a)+spawnChannelLocal f = spawnChannelLocalP $ evalSessionEq . f++spawnChannelLocalP :: Serializable a => (P.ReceivePort a -> P.Process ()) -> Session s s (P.SendPort a)+spawnChannelLocalP = liftP . P.spawnChannelLocal++callLocal :: Session s s a -> Session s s a+callLocal sess = callLocalP $ evalSessionEq sess++callLocalP :: P.Process a -> Session s s a+callLocalP = liftP . P.callLocal++reconnect :: P.ProcessId -> Session s s ()+reconnect = liftP . P.reconnect++reconnectPort :: P.SendPort a -> Session s s ()+reconnectPort = liftP . P.reconnectPort
+ src/Control/Distributed/Session/Normalize.hs view
@@ -0,0 +1,91 @@+{-# LANGUAGE DataKinds #-}+-- | This module provides three functions for normalizing session typed programs.+--+-- With normalizing we mean that we apply rewrites to a session typed program until we can no longer do so+-- and that do not change the semantics of the program.+--+-- The motivation for this module is that for two session typed programs to run as a session they must be dual.+-- Sometimes, one of these programs might not have a session type that is dual to the session type of the other program,+--+-- but we can rewrite the program and therefore also its session type. It is of course important that we do not+-- alter the semantics of the program when rewriting it. For that reason, any rewrite that we may apply must be isomorphic.+--+-- A rewrite is isomorphic if we have two programs \p\ and \p'\, we can do a rewrite from \p\ to \p'\ and from \p'\ to \p\.+--+-- For now two types of rewrites are applied: Elimination of recursive types and flattening of branches.+--+-- An additional benefit of normalizing is that it may lead to further optimizations. +-- +-- In "Control.Distributed.Session.Eval" we send an integer for every `Sel` session type that we encounter. By flattening branching+-- we reduce the number of `Sel` constructors and therefore also the number of times one needs to communicate an integer. +module Control.Distributed.Session.Normalize (+ normalize,+ elimRec,+ flatten+) where++import Control.SessionTypes+import Control.SessionTypes.Codensity (rep)+import qualified Control.SessionTypes.Normalize as S++import Control.Distributed.Session.Session++-- | Applies two types of rewrites to a `Session`.+--+-- * Elimination of unused recursion+-- * Rewrites non-right nested branchings to right nested branchings+normalize :: S.Normalize s s' => Session s ('Cap '[] Eps) a -> Session s' ('Cap '[] Eps) a+normalize sess = Session $ \si -> rep $ S.normalize (runSession sess si)++-- | Function for eliminating unused recursive types.+--+-- The function `elimRec` takes a `Session` and traverses the underlying `STTerm`. While doing so, it will attempt to remove `STTerm` constructors annotated with `R` or `Wk` from the program+-- if in doing so does not change the behavior of the program.+--+-- For example, in the following session type we may remove the inner `R` and the `Wk`. +--+-- > R (R (Wk V))+--+-- We have that the outer `R` matches the recursion variable because of the use of `Wk`. +--+-- That means the inner `R` does not match any recursion variable (the `R` is unused) and therefore may it and its corresponding constructor be removed from the session.+--+-- We also remove the `Wk`, because the session type pushed into the context by the inner `R` has also been removed.+-- +-- The generated session type is+--+-- > R V+elimRec :: S.ElimRec s s' => Session s ('Cap '[] Eps) a -> Session s' ('Cap '[] Eps) a+elimRec sess = Session $ \si -> rep $ S.elimRec (runSession sess si)++-- | Flattening of branching+--+-- The function `flatten` takes a `Session` and traverses the underlying `STTerm`. +-- If it finds a branching session type that has a branch+-- starting with another branching of the same type, then it will extract the branches of the inner branching+-- and inserts these into the outer branching. This is similar to flattening a list of lists to a larger list.+--+-- For example:+--+-- > Sel '[a,b, Sel '[c,d], e]+--+-- becomes+--+-- > Sel '[a,b,c,d,e]+--+-- This only works if the inner branching has the same type as the outer branch (Sel in Sel or Off in Off).+--+-- Also, for now this rewrite only works if one of the branching of the outer branch starts with a new branching.+--+-- For example:+--+-- > Sel '[a,b, Int :!> Sel '[c,d],e]+--+-- does not become+--+-- > Sel '[a,b,Int :!> c, Int :!> d, e]+--+-- Although, this is something that will be added in the future.+flatten :: S.Flatten s s' => Session s ('Cap '[] Eps) a -> Session s' ('Cap '[] Eps) a+flatten sess = Session $ \si -> rep $ S.flatten (runSession sess si)+
+ src/Control/Distributed/Session/STChannel.hs view
@@ -0,0 +1,245 @@+{-# LANGUAGE ExistentialQuantification #-}+{-# LANGUAGE TypeOperators #-}+{-# LANGUAGE DeriveGeneric #-}+{-# LANGUAGE StandaloneDeriving #-}+{-# LANGUAGE ScopedTypeVariables #-}+{-# LANGUAGE DataKinds #-}+{-# LANGUAGE KindSignatures #-}+{-# LANGUAGE MultiParamTypeClasses #-}+{-# LANGUAGE FlexibleInstances #-}+{-# LANGUAGE TypeFamilies #-}+-- | Defines a session typed channel as a wrapper over the typed channel from Cloud Haskell+--+-- We define a session typed channel to overcome the limitation of a typed channel that can only send and receive messages of a single type.+--+-- Underneath we actually do the same, and make use of `unsafeCoerce` to coerce a value's type to that described in the session typed.+--+-- Session types do not entirely guarantee safety of using `unsafeCoerce`. One can use the same session typed send port over and over again,+-- while the correpsonding receive port might progress through the session type resulting in a desync of types between the send and receive port.+--+-- It is for this reason recommended to always make use of `STChannelT` that always progresses the session type of a port after a session typed action.+module Control.Distributed.Session.STChannel (+ -- * Data types+ Message(..),+ STSendPort(..),+ STReceivePort(..),+ -- * Type synonyms+ STChan,+ STChanBi,+ UTChan,+ -- * Create+ newSTChan,+ newSTChanBi,+ newUTChan,+ toSTChan,+ toSTChanBi,+ sendProxy,+ recvProxy,+ -- * Usage+ sendSTChan,+ recvSTChan,+ STSplit(..),+ STRec(..),+ -- * Channel transformer+ STChannelT(..),+ sendSTChanM,+ recvSTChanM,+ sel1ChanM,+ sel2ChanM,+ off1ChanM,+ off2ChanM,+ recChanM,+ wkChanM,+ varChanM,+ epsChanM+) where++import qualified Control.SessionTypes.Indexed as IM+import Control.SessionTypes.Types++import qualified Control.Distributed.Process as P+import Control.Distributed.Process.Serializable++import qualified Data.ByteString.Lazy as BSL+import Data.Binary+import Data.Typeable+import Data.Kind (Type)+import Unsafe.Coerce++-- | Basic message type that existentially quantifies the content of the message+data Message = forall a. Serializable a => Message a deriving Typeable++instance Binary Message where+ put (Message msg) = put $ BSL.toChunks (encode msg)+ get = (Message . BSL.fromChunks) <$> get++-- | Session typed send port as a wrapper over SendPort Message. It is parameterized with a capability/sessiontype.+data STSendPort (l :: Cap Type) = STSendPort (P.SendPort Message)+-- | Session typed receive port as a wrapper over ReceivePort Message. It is parameterized with a capability/sessiontype.+data STReceivePort (l :: Cap Type) = STReceivePort (P.ReceivePort Message)++-- | Type synonym for a session typed channel given a single session type+--+-- This removes recv session types from the given session type as it is passed to the send port type+--+-- Also removes send session types from the given session type as it is passed to the receive port type+type STChan s = (STSendPort (RemoveRecv s), STReceivePort (RemoveSend s))+-- | Same as `STChan`, but it is given a session type for the send port type and a separate session type for the receive port type+type STChanBi s r = (STSendPort (RemoveRecv s), STReceivePort (RemoveSend r))+-- | Unsession typed typed channel+--+-- It is essentially just a typed channel that is parameterized with `Message`.+--+-- We can carry around this type in `Session`, but not a `STChan`.+type UTChan = (P.SendPort Message, P.ReceivePort Message)++-- | Creates a new session typed channel given a single session type+newSTChan :: Proxy s -> P.Process (STChan s)+newSTChan _ = do+ (s, r) <- P.newChan+ return $ (STSendPort s, STReceivePort r)++-- | Creates a new session typed channel given separate session types for the send port and receive port+newSTChanBi :: Proxy s -> Proxy r -> P.Process (STChanBi s r)+newSTChanBi _ _ = do+ (s, r) <- P.newChan+ return $ (STSendPort s, STReceivePort r)++-- | Creates an unsession typed channel+newUTChan :: P.Process UTChan+newUTChan = P.newChan++-- | Converts an unsession typed channel to a session typed channel+toSTChan :: UTChan -> Proxy s -> STChan s+toSTChan (sport, rport) _ = (STSendPort sport, STReceivePort rport)++-- | Converts an unsession typed channel to a session typed channel+toSTChanBi :: UTChan -> Proxy s -> Proxy r -> STChanBi s r+toSTChanBi (sport, rport) _ _ = (STSendPort sport, STReceivePort rport)++-- | Converts a session typed send port into a Proxy+sendProxy :: STSendPort s -> Proxy s+sendProxy _ = Proxy++-- | Converts a session typed receive port into a Proxy+recvProxy :: STReceivePort s -> Proxy s+recvProxy _ = Proxy++-- | Sends a message using a session typed send port+sendSTChan :: Serializable a => STSendPort ('Cap ctx (a :!> l)) -> a -> P.Process (STSendPort ('Cap ctx l))+sendSTChan (STSendPort s) a = do+ P.sendChan s $ Message a+ return $ STSendPort s ++-- | Receives a message using a session typed receive port+recvSTChan :: Serializable a => STReceivePort ('Cap ctx (a :?> l)) -> P.Process (a, STReceivePort ('Cap ctx l))+recvSTChan (STReceivePort p) = do+ (Message b) <- P.receiveChan p+ return (unsafeCoerce b, STReceivePort p)++-- | Type class that defines combinators for branching on a session typed port+class STSplit (m :: Cap Type -> Type) where+ -- | select the first branch of a selection using the given port+ sel1Chan :: m ('Cap ctx (Sel (s ': xs))) -> m ('Cap ctx s)+ -- | select the second branch of a selection using the given port+ sel2Chan :: m ('Cap ctx (Sel (s ': t ': xs))) -> m ('Cap ctx (Sel (t ': xs)))+ -- | select the first branch of an offering using the given port+ off1Chan :: m ('Cap ctx (Off (s ': xs))) -> m ('Cap ctx s)+ -- | select the second branch of an offering using the given port+ off2Chan :: m ('Cap ctx (Off (s ': t ': xs))) -> m ('Cap ctx (Off (t ': xs)))++instance STSplit STSendPort where+ sel1Chan (STSendPort s) = STSendPort s+ sel2Chan (STSendPort s) = STSendPort s+ off1Chan (STSendPort s) = STSendPort s+ off2Chan (STSendPort s) = STSendPort s++instance STSplit STReceivePort where+ sel1Chan (STReceivePort s) = STReceivePort s+ sel2Chan (STReceivePort s) = STReceivePort s+ off1Chan (STReceivePort s) = STReceivePort s+ off2Chan (STReceivePort s) = STReceivePort s++-- | Type class for recursion on a session typed port+class STRec (m :: Cap Type -> Type) where+ recChan :: m ('Cap ctx (R s)) -> m ('Cap (s ': ctx) s)+ wkChan :: m ('Cap (t ': ctx) (Wk s)) -> m ('Cap ctx s)+ varChan :: m ('Cap (s ': ctx) V) -> m ('Cap (s ': ctx) s)++instance STRec STSendPort where+ recChan (STSendPort s) = STSendPort s+ wkChan (STSendPort s) = STSendPort s+ varChan (STSendPort s) = STSendPort s++instance STRec STReceivePort where+ recChan (STReceivePort s) = STReceivePort s+ wkChan (STReceivePort s) = STReceivePort s+ varChan (STReceivePort s) = STReceivePort s++-- | Indexed monad transformer that is indexed by two products of session types+--+-- This monad also acts as a state monad that whose state is defined by a session typed channel and dependent on the indexing of the monad.+data STChannelT m (p :: Prod Type) (q :: Prod Type) a = STChannelT { + runSTChannelT :: ( (STSendPort (Left p), STReceivePort (Right p)) -> + m (a, (STSendPort (Left q), STReceivePort (Right q)))) + }++instance Monad m => IM.IxFunctor (STChannelT m) where+ fmap f (STChannelT g) = STChannelT $ \c -> g c >>= \(a, c') -> return (f a, c')++instance Monad m => IM.IxApplicative (STChannelT m) where+ pure = IM.return+ (STChannelT f) <*> (STChannelT g) = STChannelT $ \c -> f c >>= \(f', c') -> g c' >>= \(a, c'') -> return (f' a, c'')++instance Monad m => IM.IxMonad (STChannelT m) where+ return a = STChannelT $ \c -> return (a, c)+ (STChannelT f) >>= g = STChannelT $ \c -> f c >>= \(a, c') -> runSTChannelT (g a) c'++instance Monad m => IM.IxMonadT STChannelT m where+ lift m = STChannelT $ \c -> m >>= \a -> return (a, c)++-- | Send a message+--+-- Only the session type of the send port needs to be adjusted+sendSTChanM :: Serializable a => a -> STChannelT P.Process ('Cap ctx (a :!> l) :*: r) ('Cap ctx l :*: r) ()+sendSTChanM a = STChannelT $ \(sp, rp) -> sendSTChan sp a >>= \sp' -> return ((), (sp', rp))++-- | receive a message+--+-- Only the session type of the receive port needs to be adjusted+recvSTChanM :: Serializable a => STChannelT P.Process (l :*: ('Cap ctx (a :?> r))) (l :*: 'Cap ctx r) a+recvSTChanM = STChannelT $ \(sp, rp) -> recvSTChan rp >>= \(a, rp') -> return (a, (sp, rp'))++-- | select the first branch of a selection+--+-- Both ports are now adjusted. This is similarly so for the remaining combinators.+sel1ChanM :: STChannelT P.Process ('Cap lctx (Sel (l ': ls)) :*: ('Cap rctx (Sel (r ': rs)))) ('Cap lctx l :*: 'Cap rctx r) ()+sel1ChanM = STChannelT $ \(sp, rp) -> return ((), (sel1Chan sp, sel1Chan rp))++-- | select the second branch of a selection+sel2ChanM :: STChannelT P.Process ('Cap lctx (Sel (s1 ': t1 ': xs1)) :*: 'Cap rctx (Sel (s2 ': t2 ': xs2))) ('Cap lctx (Sel (t1 ': xs1)) :*: 'Cap rctx (Sel (t2 ': xs2))) ()+sel2ChanM = STChannelT $ \(sp, rp) -> return ((), (sel2Chan sp, sel2Chan rp))++-- | select the first branch of an offering+off1ChanM :: STChannelT P.Process ('Cap lctx (Off (l ': ls)) :*: ('Cap rctx (Off (r ': rs)))) ('Cap lctx l :*: 'Cap rctx r) ()+off1ChanM = STChannelT $ \(sp, rp) -> return ((), (off1Chan sp, off1Chan rp))++-- | select the second branch of an offering+off2ChanM :: STChannelT P.Process ('Cap lctx (Off (s1 ': t1 ': xs1)) :*: 'Cap rctx (Off (s2 ': t2 ': xs2))) ('Cap lctx (Off (t1 ': xs1)) :*: 'Cap rctx (Off (t2 ': xs2))) ()+off2ChanM = STChannelT $ \(sp, rp) -> return ((), (off2Chan sp, off2Chan rp))++-- | delimit scope of recursion+recChanM :: STChannelT P.Process ('Cap sctx (R s) :*: 'Cap rctx (R r)) ('Cap (s ': sctx) s :*: 'Cap (r ': rctx) r) ()+recChanM = STChannelT $ \(sp, rp) -> return ((), (recChan sp, recChan rp))++-- | weaken scope of recursion+wkChanM :: STChannelT P.Process ('Cap (t ': sctx) (Wk s) :*: 'Cap (k ': rctx) (Wk r)) ('Cap sctx s :*: 'Cap rctx r) ()+wkChanM = STChannelT $ \(sp, rp) -> return ((), (wkChan sp, wkChan rp)) ++-- | recursion variable (recurse here)+varChanM :: STChannelT P.Process (('Cap (s ': sctx) V) :*: ('Cap (r ': rctx) V)) ('Cap (s ': sctx) s :*: 'Cap (r ': rctx) r) ()+varChanM = STChannelT $ \(sp, rp) -> return ((), (varChan sp, varChan rp))++-- | ports are no longer usable+epsChanM :: STChannelT P.Process ('Cap ctx Eps :*: 'Cap ctx Eps) ('Cap ctx Eps :*: 'Cap ctx Eps) ()+epsChanM = STChannelT $ \utchan -> return ((), utchan)
+ src/Control/Distributed/Session/Session.hs view
@@ -0,0 +1,81 @@+{-# LANGUAGE RebindableSyntax #-}+{-# LANGUAGE FlexibleInstances #-}+{-# LANGUAGE MultiParamTypeClasses #-}+-- | This module defines the `Session` session typed indexed monad.+module Control.Distributed.Session.Session (+ -- * Data types+ Session(..),+ SessionInfo(..),+ runSession,+ -- * Lifting+ liftP,+ liftST+) where++import Control.SessionTypes+import Control.SessionTypes.Codensity+import Control.SessionTypes.Indexed hiding (abs)+import Control.Distributed.Session.STChannel (UTChan)++import Control.Distributed.Process as P (Process, ProcessId, NodeId, liftIO)++-- | `Session` is defined as a newtype wrapper over a function that takes a `Maybe SessionInfo` and returns an indexed codensity monad transformer over the `Process` monad.+--+-- `Session` is also a reader monad that has a Maybe SessionInfo as its environment. `SessionInfo` is wrapped in a `Maybe`, because we also allow a session to be run singularly.+-- In which case there is no other Session to communicate with and therefore is there also no need for a `SessionInfo`.+--+-- The function returns the indexed codensity monad and not simply a `STTerm`, because from benchmarking the codensity monad gave us significant performance improvements for free.+newtype Session s r a = Session { runSessionC :: Maybe SessionInfo -> IxC Process s r a }++-- | The SessionInfo data type tells us information about another `Session`. Namely, the `Session` that is in a session with the `Session` that this specific `SessionInfo` belongs to. +data SessionInfo = SessionInfo {+ othPid :: ProcessId, -- ^ The `ProcessId` of the dual `Session`+ othNode :: NodeId, -- ^ The `NodeId` of the `Node` that the dual `Session` runs on+ utchan :: UTChan -- ^ A send port belonging to the dual `Session`, such that we can send messages to it. And a receive port of which the dual `Session` has its send port, such that we can receive messages from the dual `Session`.+}++-- | Evaluates a session to a `STTerm`+runSession :: Session s r a -> Maybe SessionInfo -> STTerm Process s r a+runSession (Session c) si = abs $ c si++instance IxFunctor Session where+ fmap f sess = Session $ \si -> fmap f $ runSessionC sess si++instance IxApplicative Session where+ pure = return+ f <*> g = Session $ \si -> (runSessionC f si) <*> (runSessionC g si)++instance IxMonad Session where+ return a = Session $ \_ -> return a+ (Session s) >>= f = Session $ \si -> do+ a <- s si+ let (Session r) = f a+ r si++instance MonadSession Session where+ send a = Session $ const $ send a+ recv = Session $ const recv+ sel1 = Session $ const sel1+ sel2 = Session $ const sel2+ offZ (Session f) = Session $ offZ . f+ offS (Session f) (Session g) = Session $ \si -> offS (f si) (g si) + recurse (Session f) = Session $ \si -> recurse (f si)+ weaken (Session f) = Session $ \si -> weaken (f si)+ var (Session f) = Session $ \si -> var $ f si+ eps a = Session $ const $ eps a++instance IxMonadReader (Maybe SessionInfo) Session where+ ask = Session $ \si -> return si+ local f m = Session $ \si -> runSessionC m (f si)+ reader f = Session $ \si -> return (f si)++instance IxMonadIO Session where+ liftIO = liftP . P.liftIO++-- | Lifts a `Process` computation+liftP :: Process a -> Session s s a+liftP p = Session $ \_ -> rep $ lift p++-- | Lifts a `STTerm` computation+liftST :: STTerm Process s r a -> Session s r a+liftST st = Session $ \_ -> rep st
+ src/Control/Distributed/Session/Spawn.hs view
@@ -0,0 +1,268 @@+-- | Defines several combinators for spawning sessions+--+-- Here we define a session to be two dual `Session`s that together implement a protocol described by a session type.+--+-- The following shows an example of how to spawn a session+--+-- @+--+-- {-\# LANGUAGE TemplateHaskell \#-}+-- {-\# LANGUAGE DataKinds \#-}+-- {-\# LANGUAGE TypeOperators \#-}+-- +-- import qualified SessionTypes.Indexed as I+-- import Control.Distributed.Session hiding (getSelfPid, expect)+-- import Control.Distributed.Process (liftIO, Process, RemoteTable, NodeId, getSelfPid, ProcessId, expect)+-- import Control.Distributed.Process.Closure (remotable, mkClosure)+-- import Control.Distributed.Process.Node+-- import Network.Transport.TCP+-- +-- sess1 :: Session ('Cap '[] (Int :!> Eps)) ('Cap '[] Eps) ()+-- sess1 = send 5 I.>> eps ()+-- +-- sess2 :: ProcessId -> Session ('Cap '[] (Int :?> Eps)) ('Cap '[] Eps) ()+-- sess2 pid = recv I.>>= \x -> utsend pid x I.>>= eps+-- +-- spawnSess :: ProcessId -> SpawnSession () ()+-- spawnSess pid = SpawnSession sess1 (sess2 pid)+-- +-- remotable ['spawnSess]+-- +-- p1 :: NodeId -> Process ()+-- p1 nid = do+-- pid <- getSelfPid+-- spawnRRSessionP nid nid ($(mkClosure 'spawnSess) pid)+-- a <- expect :: Process Int+-- liftIO (putStrLn $ show a)+-- +-- myRemoteTable :: RemoteTable+-- myRemoteTable = Main.__remoteTable $ sessionRemoteTable initRemoteTable+-- +-- main :: IO ()+-- main = do+-- Right t <- createTransport "127.0.0.1" "100000" defaultTCPParameters+-- node <- newLocalNode t myRemoteTable+-- runProcess node $ p1 (localNodeId node)+--+-- @+--+-- >>> main+-- > 5+--+-- In p1 we spawn a session that consists of two `Session`s that are remotely spawned (which happens to be the local node).+--+-- We do so using the `spawnRRSessionP` function that we can call within a `Process`. We pass it the two node identifiers followed+-- by a closure that takes an argument.+--+-- Sess1 and sess2 implement both sides of the protocol. We can insert these into a `SpawnSession`, because they are dual to each other.+-- +-- > spawnSess :: ProcessId -> SpawnSession () ()+-- > spawnSess pid = SpawnSession sess1 (sess2 pid)+--+-- Then to create a closure for `spawnSess` that we can then pass to `spawnRRSessionP` we first add `spawnSess` to the remotable of the current module.+--+-- > remotable ['spawnSess]+--+-- remotable is a top-level Template Haskell splice that creates a closure function for us.+--+-- To use this closure function we can simply do+--+-- > $(mkClosure 'spawnSess) pid+--+-- We use `mkClosure` such that we can still pass an argument to spawnSess with the result being of type Closure (SpawnSession () ())+--+-- It is important that the node that we run p1 on knows how to evaluate a closure of type Closure (SpawnSession () ()). This requires that we +-- compose the initRemoteTable of a node with the remotable of this module.+--+-- Within `spawnRRSessionP` we make use of internally defined closures. The library therefore exports `sessionRemoteTable` that should always be passed to a node+-- if you make use of a function within this library that takes a closure as an argument. +--+-- > myRemoteTable :: RemoteTable+-- > myRemoteTable = Main.__remoteTable $ sessionRemoteTable initRemoteTable+--+-- > node <- newLocalNode t myRemoteTable+module Control.Distributed.Session.Spawn (+ -- * Call+ callLocalSessionP,+ callLocalSession,+ callRemoteSessionP,+ callRemoteSession,+ callRemoteSessionP',+ callRemoteSession',+ -- * Spawn+ spawnLLSessionP,+ spawnLLSession,+ spawnLRSessionP,+ spawnLRSession,+ spawnRRSessionP,+ spawnRRSession+) where++import Control.Distributed.Process as P+import Control.Distributed.Process.Serializable+import Control.SessionTypes+import Control.Distributed.Session.Closure+import Control.Distributed.Session.Eval+import Control.Distributed.Session.Session+import Control.Distributed.Session.STChannel as ST++import Control.Concurrent++-- | Calls a local session consisting of two dual `Session`s. +-- +-- Spawns a new local process for the second `Session` and runs the first `Session` on the current process.+--+-- Returns the result of the first `Session` and the `ProcessId` of the second `Session`.+callLocalSessionP :: (HasConstraint Serializable s, + HasConstraint Serializable (Dual s)) => + Session s r a -> Session (Dual s) r b -> P.Process (a, ProcessId)+callLocalSessionP s1 s2 = do+ pidSelf <- P.getSelfPid+ node <- P.getSelfNode+ (sp1, rp1) <- ST.newUTChan+ (sp2, rp2) <- ST.newUTChan++ let si1 = SessionInfo pidSelf node (sp1, rp2) + pid <- P.spawnLocal $ evalSession s2 si1 >> return ()+ let si2 = SessionInfo pid node (sp2, rp1)+ a <- evalSession s1 si2+ + return (a, pid)++-- | Sessioned version of `callLocalSessionP`+callLocalSession :: (HasConstraint Serializable s,+ HasConstraint Serializable (Dual s)) =>+ Session s r a -> Session (Dual s) r b -> Session k k (a, ProcessId)+callLocalSession ss1 ss2 = liftP $ callLocalSessionP ss1 ss2++-- | Calls a remote session consisting of two dual `Session`s.+--+-- Spawns a remote process for the second `Session` and runs the first `Session` on the current process.+--+-- Returns the result of the frist `Session` and the `ProcessId` of the second `Session`.+--+-- The arguments of this function are described as follows:+--+-- * Static (SerializableDict a): Describes how to serialize a value of type `a`+-- * NodeId: The node identifier of the node that the second `Session` should be spawned to.+-- * Closure (SpawnSession a ()): A closure of a wrapper over two dual `Session`s.+--+-- Requires `sessionRemoteTable`+callRemoteSessionP :: Serializable a => Static (SerializableDict a) -> NodeId -> Closure (SpawnSession a ()) -> Process (a, ProcessId)+callRemoteSessionP sdict nodeOth proc = do+ pidSelf <- getSelfPid+ nodeSelf <- getSelfNode++ pidOth <- spawn nodeOth $ remoteSpawnSessionClosure sdict ((pidSelf, nodeSelf, proc))+ a <- evalLocalSession (pidOth, nodeOth, proc)+ return (a, pidOth)++-- | Sessioned version of `callRemoteSession`+--+-- Requires `sessionRemoteTable`+callRemoteSession :: Serializable a => Static (SerializableDict a) -> NodeId -> Closure (SpawnSession a ()) -> Session k k (a, ProcessId)+callRemoteSession n1 sdict proc = liftP $ callRemoteSessionP n1 sdict proc++-- | Same as `callRemoteSessionP`, but we no longer need to provide a static serializable dictionary, because the result type of the first session is unit.+--+-- Requires `sessionRemoteTable`+callRemoteSessionP' :: NodeId -> Closure (SpawnSession () ()) -> Process (ProcessId)+callRemoteSessionP' nodeOth proc = do+ pidSelf <- getSelfPid+ nodeSelf <- getSelfNode++ pidOth <- spawn nodeOth $ remoteSpawnSessionClosure' (pidSelf, nodeSelf, proc)+ evalLocalSession (pidOth, nodeOth, proc)+ return pidOth++-- | Sessioned version of `callRemoteSessionP'`+--+-- Requires `sessionRemoteTable`+callRemoteSession' :: NodeId -> Closure (SpawnSession () ()) -> Session s s (ProcessId)+callRemoteSession' node proc = liftP $ callRemoteSessionP' node proc++-- | Spawns a local session.+--+-- Both `Session`s are spawned locally.+--+-- Returns the `ProcessId` of both spawned processes.+spawnLLSessionP :: (HasConstraint Serializable s,+ HasConstraint Serializable (Dual s)) =>+ Session s r a -> Session (Dual s) r b -> Process (ProcessId, ProcessId)+spawnLLSessionP sess1 sess2 = do+ nodeSelf <- getSelfNode+ mvar <- liftIO newEmptyMVar+ (sp1, rp1) <- ST.newUTChan+ (sp2, rp2) <- ST.newUTChan++ pid1 <- spawnLocal $ do+ pid <- liftIO $ takeMVar mvar+ evalSession sess1 (SessionInfo pid nodeSelf (sp1, rp2))+ return ()++ pid2 <- spawnLocal $ do+ pid <- getSelfPid+ liftIO $ putMVar mvar pid+ evalSession sess2 (SessionInfo pid1 nodeSelf (sp2, rp1))+ return ()++ return (pid1, pid2)++-- | Sessioned version of `spawnLLSession`+spawnLLSession :: (HasConstraint Serializable s,+ HasConstraint Serializable (Dual s)) =>+ Session s r a -> Session (Dual s) r b -> Session t t (ProcessId, ProcessId)+spawnLLSession st1 st2 = liftP $ spawnLLSessionP st1 st2++-- | Spawns one `Session` local and spawns another `Session` remote.+--+-- Returns the `ProcessId` of both spawned processes.+--+-- The arguments are described as follows:+--+-- * NodeId: The node identifier of the node that the second `Session` should be spawned to.+-- * Closure (SpawnSession () ()): A closure of a wrapper over two dual `Session`s.+--+-- Requires `sessionRemoteTable`+spawnLRSessionP :: NodeId -> Closure (SpawnSession () ()) -> Process (ProcessId, ProcessId)+spawnLRSessionP nodeOth proc = do+ nodeSelf <- getSelfNode+ mvar <- liftIO newEmptyMVar++ pid1 <- spawnLocal $ do+ pid <- liftIO $ takeMVar mvar+ evalLocalSession (pid, nodeOth, proc)+ pid2 <- spawn nodeOth $ remoteSpawnSessionClosure' ((pid1, nodeSelf, proc))+ liftIO $ putMVar mvar pid2++ return (pid1, pid2)++-- | Sessioned version of `spawnLRSessionP`+--+-- Requires `sessionRemoteTable`+spawnLRSession :: NodeId -> Closure (SpawnSession () ()) -> Session s s (ProcessId, ProcessId)+spawnLRSession node proc = liftP $ spawnLRSessionP node proc++-- | Spawns a remote session. Both `Session` arguments are spawned remote.+--+-- Returns the `ProcessId` of both spawned processes.+--+-- The arguments are described as follows:+--+-- * NodeId: The node identifier of the node that the first `Session` should be spawned to.+-- * NodeId: The node identifier of the node that the second `Session` should be spawned to.+-- * Closure (SpawnSession () ()): A closure of a wrapper over two dual `Session`s.+--+-- Requires `sessionRemoteTable`+spawnRRSessionP :: NodeId -> NodeId -> Closure (SpawnSession () ()) -> Process (ProcessId, ProcessId)+spawnRRSessionP n1 n2 proc = do+ pid1 <- spawn n1 (rrSpawnSessionExpectClosure (n2, proc)) -- expect a pid+ pid2 <- spawn n2 (rrSpawnSessionSendClosure (pid1, n1, proc)) -- send a pid++ return (pid1, pid2)++-- | Sessioned version of `SpawnRRSession`+--+-- Requires `sessionRemoteTable`+spawnRRSession :: NodeId -> NodeId -> Closure (SpawnSession () ()) -> Session s s (ProcessId, ProcessId)+spawnRRSession n1 n2 proc = liftP $ spawnRRSessionP n1 n2 proc
+ src/Control/Distributed/Session/Visualize.hs view
@@ -0,0 +1,9 @@+{-# LANGUAGE ScopedTypeVariables #-}+{-# LANGUAGE PolyKinds #-}+{-# LANGUAGE DataKinds #-}+module Control.Distributed.Session.Visualize (+ visualize,+ visualizeP+) where++import Control.SessionTypes.Visualize as V (visualize, visualizeP)
+ test/Test/Lifted/Main.hs view
@@ -0,0 +1,55 @@+{-# LANGUAGE TemplateHaskell #-}+import Control.Distributed.Session (evalSessionEq, sessionRemoteTable, spawnChannel, call, spawn)+import Control.Distributed.Process (Process, NodeId, RemoteTable, liftIO, getSelfPid, sendChan, expect)+import Control.Distributed.Process.Node+import Control.Distributed.Process.Closure+import Network.Transport.TCP++import Test.Hspec+import Test.Program.Closure++main :: IO ()+main = do+ n <- newNode 10010+ runProcess n $ do+ let nid = localNodeId n+ x1 <- test_call nid+ x2 <- test_spawn nid+ x3 <- test_spawnChannel nid++ liftIO $ do+ hspec $ do+ describe "call" $ do+ it "spawns a `Session` on a remote node and waits for its result" $+ x1 `shouldBe` 5++ describe "spawn" $ do+ it "spawns a `Session` on a remote node" $+ x2 `shouldBe` 5++ describe "spawnChannel" $ do+ it "spawns a `Session` on a remote node together with a typed channel" $+ x3 `shouldBe` 6+ +myRemoteTable :: RemoteTable+myRemoteTable = Test.Program.Closure.__remoteTable $ sessionRemoteTable initRemoteTable++newNode p = do+ Right t <- createTransport "127.0.0.1" (show p) defaultTCPParameters+ newLocalNode t myRemoteTable++test_call :: NodeId -> Process Int+test_call nid = evalSessionEq $ call $(mkStatic 'sdictInt) nid $(mkStaticClosure 'sessWrap)++test_spawn :: NodeId -> Process Int+test_spawn nid = do+ pid <- getSelfPid+ evalSessionEq $ spawn nid ($(mkClosure 'sessSpawnWrap) pid)+ expect++test_spawnChannel :: NodeId -> Process Int+test_spawnChannel nid = do+ pid <- getSelfPid+ sp <- evalSessionEq $ spawnChannel $(mkStatic 'sdictInt) nid ($(mkClosure 'spawnChWrap) pid)+ sendChan sp 6+ expect
+ test/Test/Program/Closure.hs view
@@ -0,0 +1,68 @@+{-# LANGUAGE DataKinds #-}+{-# LANGUAGE TypeOperators #-}+{-# LANGUAGE RebindableSyntax #-}+{-# LANGUAGE TemplateHaskell #-}+module Test.Program.Closure where++import Control.SessionTypes.Indexed+import Control.Distributed.Session+import Control.Distributed.Process as P (Process, ProcessId, NodeId, ReceivePort)+import Control.Distributed.Process.Serializable (SerializableDict(..))+import Control.Distributed.Process.Closure (remotable, mkStatic, mkStaticClosure, mkClosure)++import qualified Prelude as PL++sess1 :: Session ('Cap '[] (R (Int :?> Sel '[V, Wk Eps]))) ('Cap '[] Eps) Int+sess1 = recurseFix $ \f -> do+ n <- recv+ liftIO (putStrLn $ show n)+ if n > 0+ then sel1 >> f+ else selN2 >> weaken0 >> eps n++sess1' :: ProcessId -> Session ('Cap '[] (R (Int :?> Sel '[V, Wk Eps]))) ('Cap '[] Eps) ()+sess1' pid = recurseFix $ \f -> do+ n <- recv+ liftIO (putStrLn $ show n)+ if n > 0+ then sel1 >> f+ else selN2 >> weaken0 >> utsend pid n >> eps ()++sess2 :: Session ('Cap '[] (R (Int :!> Off '[V, Wk Eps]))) ('Cap '[] Eps) ()+sess2 = recurse $ go 3+ where + go n = do+ send n+ offer (var $ go (n - 1)) (weaken0 >> eps0)++sessReturn :: Session s s Int+sessReturn = return 5++sessSpawnCh :: ProcessId -> ReceivePort Int -> Session s s ()+sessSpawnCh pid rp = do+ a <- receiveChan rp+ utsend pid a++sessSpawn :: ProcessId -> Session s s ()+sessSpawn pid = utsend pid (5 :: Int)++spawnSess :: SpawnSession Int ()+spawnSess = SpawnSession sess1 sess2++spawnSess0 :: ProcessId -> SpawnSession () ()+spawnSess0 pid = SpawnSession (sess1' pid) sess2++sessWrap :: SessionWrap Int+sessWrap = SessionWrap sessReturn++spawnChWrap :: ProcessId -> ReceivePort Int -> SessionWrap ()+spawnChWrap pid rp = SessionWrap $ sessSpawnCh pid rp++sessSpawnWrap :: ProcessId -> SessionWrap ()+sessSpawnWrap pid = SessionWrap $ sessSpawn pid++sdictInt :: SerializableDict Int+sdictInt = SerializableDict++remotable ['spawnSess, 'spawnSess0, 'sdictInt, 'sessWrap, 'spawnChWrap, 'sessSpawnWrap]+
+ test/Test/Spawn/Main.hs view
@@ -0,0 +1,85 @@+{-# LANGUAGE TemplateHaskell #-}+import Control.Distributed.Session.Spawn+import Control.Distributed.Session.Closure+import Control.Distributed.Process+import Control.Distributed.Process.Node+import Control.Distributed.Process.Closure+import Network.Transport.TCP++import Test.Hspec+import Test.Program.Closure++main :: IO ()+main = do+ n <- newNode 10000+ runProcess n $ do+ let nid = localNodeId n+ x1 <- test_callLocalSession+ x2 <- test_callRemoteSession nid + x3 <- test_callRemoteSession' nid+ x4 <- test_spawnLLSession+ x5 <- test_spawnLRSession nid+ x6 <- test_spawnRRSession nid++ liftIO $ do+ hspec $ do+ describe "callLocalSession" $ do+ it "spawns a session and waits for the result of the first process" $ do+ x1 `shouldBe` 0++ describe "callRemoteSession" $ do+ it "spawns a session and waits for the result of the first process" $ do+ x2 `shouldBe` 0++ describe "callRemoteSession'" $ do+ it "spawns a session and waits for the result of the first process" $ do+ x3 `shouldBe` 0++ describe "spawnLLSession" $ do+ it "spawns a local session" $ do+ x4 `shouldBe` 0++ describe "spawnLRSession" $ do+ it "spawns a session, one process is spawned locally and another remote" $ do+ x5 `shouldBe` 0++ describe "spawnRRSession" $ do+ it "spawns a session, both processes are spawned remote" $ do+ x6 `shouldBe` 0+ +myRemoteTable :: RemoteTable+myRemoteTable = Test.Program.Closure.__remoteTable $ sessionRemoteTable initRemoteTable++newNode p = do+ Right t <- createTransport "127.0.0.1" (show p) defaultTCPParameters+ newLocalNode t myRemoteTable++test_callLocalSession :: Process Int+test_callLocalSession = fmap fst $ callLocalSessionP sess1 sess2++test_callRemoteSession :: NodeId -> Process Int+test_callRemoteSession nid = fmap fst $ callRemoteSessionP $(mkStatic 'sdictInt) nid $(mkStaticClosure 'spawnSess)++test_callRemoteSession' :: NodeId -> Process Int+test_callRemoteSession' nid = do+ pid <- getSelfPid+ callRemoteSessionP' nid ($(mkClosure 'spawnSess0) pid)+ expect++test_spawnLLSession :: Process Int+test_spawnLLSession = do+ pid <- getSelfPid+ spawnLLSessionP (sess1' pid) sess2+ expect++test_spawnLRSession :: NodeId -> Process Int+test_spawnLRSession nid = do+ pid <- getSelfPid+ spawnLRSessionP nid ($(mkClosure 'spawnSess0) pid)+ expect++test_spawnRRSession :: NodeId -> Process Int+test_spawnRRSession nid = do+ pid <- getSelfPid+ spawnRRSessionP nid nid ($(mkClosure 'spawnSess0) pid)+ expect