Compare commits
428 Commits
graph-rewo
...
master
Author | SHA1 | Date |
---|---|---|
noah metz | 8cb97d2350 | |
noah metz | c29981da20 | |
noah metz | 810e17990c | |
noah metz | d0d07d464d | |
noah metz | 11e7df2bde | |
noah metz | 3eee736f97 | |
noah metz | 7e157068d7 | |
noah metz | b2d84b2453 | |
noah metz | 66d5e3f260 | |
noah metz | 1eff534e1a | |
noah metz | 3d28c703db | |
noah metz | a4115a4f99 | |
noah metz | ab76f09923 | |
noah metz | 6850031e80 | |
noah metz | 0b93c90aa9 | |
noah metz | 2db4655670 | |
noah metz | d7b07df798 | |
noah metz | 0bced58fd1 | |
noah metz | 8f9a759b26 | |
noah metz | c0407b094c | |
noah metz | c591fa5ace | |
noah metz | f8dad12fdb | |
noah metz | eef8451566 | |
noah metz | 7e143c9d93 | |
noah metz | 7314c74087 | |
noah metz | 1eb6479169 | |
noah metz | e16bec3997 | |
noah metz | 6942dc02db | |
noah metz | e5776e0a14 | |
noah metz | 8927077167 | |
noah metz | faab7eb52c | |
noah metz | 61565fa18c | |
noah metz | 9c534a1d33 | |
noah metz | c33f37e4cd | |
noah metz | b42753b575 | |
noah metz | df9707309f | |
noah metz | 646e6592f0 | |
noah metz | c5f95d431d | |
noah metz | 59424cecc1 | |
noah metz | 786f374b5f | |
noah metz | c54101f4a3 | |
noah metz | 520219f7b0 | |
noah metz | 8b91d0af0c | |
noah metz | 8bb1dacf23 | |
noah metz | 6580725241 | |
noah metz | 58675377fd | |
noah metz | dee7b917f7 | |
noah metz | 8d1e273331 | |
noah metz | 42e4a8f7ea | |
noah metz | c773ea2b14 | |
noah metz | ddb3854d00 | |
noah metz | f41160da68 | |
noah metz | 3052f8099f | |
noah metz | f5a08bbc48 | |
noah metz | 57156251cd | |
noah metz | 8e3510129c | |
noah metz | 3a6e562390 | |
noah metz | a061d6850c | |
noah metz | 2081771135 | |
noah metz | dbe819fd05 | |
noah metz | 39d3288094 | |
noah metz | 0e8590e22a | |
noah metz | 84aee24a21 | |
noah metz | 8a973c38b5 | |
noah metz | 0eab243659 | |
noah metz | a568adc156 | |
noah metz | 266e353c5f | |
noah metz | 95939fb020 | |
noah metz | 92bb4bf976 | |
noah metz | 193952e84d | |
noah metz | d930d78351 | |
noah metz | e299e77e78 | |
noah metz | b9bf61cf68 | |
noah metz | 4b7bc93914 | |
noah metz | 0159d0dd5a | |
noah metz | 76e1e9a17a | |
noah metz | b3bbf71c22 | |
noah metz | 08c36e0505 | |
noah metz | c4df57a932 | |
noah metz | 8c80ec9dd6 | |
noah metz | 187ffb1324 | |
noah metz | 16e25c009f | |
noah metz | c63ad91252 | |
noah metz | b32f264879 | |
noah metz | ae289705bb | |
noah metz | 190824e710 | |
noah metz | c4de49099b | |
noah metz | 0a936f50f8 | |
noah metz | 0941c6c64e | |
noah metz | 92d8dfd006 | |
noah metz | f82bbabc66 | |
noah metz | 542c5c18af | |
noah metz | 6381713972 | |
noah metz | 34162023cb | |
noah metz | 56f3cce415 | |
noah metz | 7234b11643 | |
noah metz | 302f0f42fe | |
noah metz | 7451e8e960 | |
noah metz | 9eadb00397 | |
noah metz | e042384b3f | |
noah metz | 3ef0a98a17 | |
noah metz | bb28d9bc32 | |
noah metz | 96408259d1 | |
noah metz | 5a86334d5a | |
noah metz | e93fe50b5f | |
noah metz | e013edc656 | |
noah metz | d4e0d855c7 | |
noah metz | 0fc6215448 | |
noah metz | b09e150c46 | |
noah metz | d86d424cd7 | |
noah metz | ff7046badf | |
noah metz | ab5b922a7d | |
noah metz | d34304f6ad | |
noah metz | 9ffa9d6cb2 | |
noah metz | 21224e8837 | |
noah metz | 6bfe339854 | |
noah metz | ecaf35f05d | |
noah metz | eb30b477d5 | |
noah metz | 5c70d1b18d | |
noah metz | de1a229db6 | |
noah metz | de54c87e43 | |
noah metz | dac0f1f273 | |
noah metz | 07ce005365 | |
noah metz | c4e5054e07 | |
noah metz | b47c95c5ad | |
noah metz | 045304f9f6 | |
noah metz | d0f0fb1b82 | |
noah metz | fa5facc5fc | |
noah metz | b766aadef9 | |
noah metz | 47107dec1c | |
noah metz | 15793e1415 | |
noah metz | e2f34150ef | |
noah metz | 06513a5ad6 | |
noah metz | 799b6404dd | |
noah metz | 1888cf428d | |
noah metz | 857f04efe3 | |
noah metz | 4daec4d601 | |
noah metz | 7bed89701d | |
noah metz | ba344bddcf | |
noah metz | 4ce2a642c5 | |
noah metz | f398c9659e | |
noah metz | 98f05d57f9 | |
noah metz | 98c0b7e807 | |
noah metz | b446c9078a | |
noah metz | d663314def | |
noah metz | e26ddcae37 | |
noah metz | 20c7a38044 | |
noah metz | f31beade29 | |
noah metz | 96e842decf | |
noah metz | 8770d6f433 | |
noah metz | 1d91854f6f | |
noah metz | 7d0af0eb5b | |
noah metz | 0f7a0debd6 | |
noah metz | 147f44e5ff | |
noah metz | 42cd8f4188 | |
noah metz | b9a2cceaf1 | |
noah metz | df09433b88 | |
noah metz | 47151905a0 | |
noah metz | 3a53163f36 | |
noah metz | c515128743 | |
noah metz | 5f2b97a75b | |
noah metz | 5bef8d96ba | |
noah metz | ed9c353b95 | |
noah metz | 3bc427f2a9 | |
noah metz | 6895aa7c8e | |
noah metz | 0cc7174667 | |
noah metz | 059c36663b | |
noah metz | b06c741ee3 | |
noah metz | 42597057af | |
noah metz | 09c25b1e48 | |
noah metz | e7d94414d5 | |
noah metz | d8355ab786 | |
noah metz | 887a976263 | |
noah metz | 771bf53356 | |
noah metz | 0313d6a33f | |
noah metz | 064dc72820 | |
noah metz | 0424a3970f | |
noah metz | fde2f3ddd4 | |
noah metz | 1af94520a8 | |
noah metz | 4e31a6763d | |
noah metz | b4e6123d4c | |
noah metz | e34d3ec981 | |
noah metz | 31f6c12f14 | |
noah metz | ec9a29573a | |
noah metz | 395a75fcb8 | |
noah metz | 9f9e65cf54 | |
noah metz | da58b04774 | |
noah metz | 7810859bca | |
noah metz | ad6ea0cc59 | |
noah metz | 96c2b84b6f | |
noah metz | 79e40bf3f3 | |
noah metz | f56f92a58b | |
noah metz | e92b2e508d | |
noah metz | dca4de183e | |
noah metz | fad8d8123c | |
noah metz | 891e69c775 | |
noah metz | d6a35247b0 | |
noah metz | 1a3a07336a | |
noah metz | 2dfa10b1f6 | |
noah metz | c60393d390 | |
noah metz | 641bd8febe | |
noah metz | f87571edcf | |
noah metz | 5fb1cb6d17 | |
noah metz | b92cebbe74 | |
noah metz | 5678c79798 | |
noah metz | 5f409def03 | |
noah metz | 61de2669e2 | |
noah metz | 08288f88af | |
noah metz | fc69bc3d0d | |
noah metz | b3de3144cc | |
noah metz | 27687add1b | |
noah metz | a16cf6bb38 | |
noah metz | fb7e6d02f4 | |
noah metz | d40e561728 | |
noah metz | f314b46415 | |
noah metz | 027c3d4c96 | |
noah metz | c763725a34 | |
noah metz | 027bb74887 | |
noah metz | a1ce4238cc | |
noah metz | a44b00bc97 | |
noah metz | 200e19eea7 | |
noah metz | 98893de442 | |
noah metz | 78c29d2f74 | |
noah metz | 7ebb519cd0 | |
noah metz | 9d31394707 | |
noah metz | 6b375245df | |
noah metz | 7965f8fbe6 | |
noah metz | d729698523 | |
noah metz | 26d122e3c5 | |
noah metz | 3ad969a5ca | |
noah metz | 7a7a9c95a3 | |
noah metz | c62ef57fe7 | |
noah metz | 544264f06b | |
noah metz | c34d717b52 | |
noah metz | 95a2f46d28 | |
noah metz | 70baca9e9c | |
noah metz | 4fa88dc056 | |
noah metz | 81c2e11304 | |
noah metz | cc807b3982 | |
noah metz | 186123ce01 | |
noah metz | 494d212051 | |
noah metz | 34082630b2 | |
noah metz | 294bcfb518 | |
noah metz | 89c8fba39b | |
noah metz | d2f3daf5a6 | |
noah metz | 755edf8558 | |
noah metz | fa6142d880 | |
noah metz | c4156ee146 | |
noah metz | f1c0f1e7de | |
noah metz | ff813d6c2b | |
noah metz | b3f6ea67c9 | |
noah metz | 4e69ba19f6 | |
noah metz | 54e25ba602 | |
noah metz | 89b082fc8e | |
noah metz | a72124e659 | |
noah metz | a2395189a8 | |
noah metz | 59df9f04d5 | |
noah metz | f118dde221 | |
noah metz | 6a2ed50578 | |
noah metz | cfc1048007 | |
noah metz | 264f31ad9a | |
noah metz | 5c3a14bdbd | |
noah metz | bd9e0a6d6f | |
noah metz | 8c12eae3a7 | |
noah metz | 8e191543d6 | |
noah metz | 24285ba5da | |
noah metz | 42fcbc240a | |
noah metz | c014ceb12c | |
noah metz | aa960b9420 | |
noah metz | cf35d8a86d | |
noah metz | 3fa550ab29 | |
noah metz | 2e77b811d5 | |
noah metz | 7d04923b3b | |
noah metz | fc2e36043f | |
noah metz | 201ee7234b | |
noah metz | fa10ccd743 | |
noah metz | c64dd728ed | |
noah metz | 3ce1e3ad91 | |
noah metz | a97b47af1b | |
noah metz | 8d94e04b07 | |
noah metz | fc6c198ae3 | |
noah metz | 32ac1f618d | |
noah metz | dfa420757b | |
noah metz | d56245c5cf | |
noah metz | 63fb5e3187 | |
noah metz | 054fe3c0ec | |
noah metz | 8fb0cbc982 | |
noah metz | 575912d56f | |
noah metz | e347a3f232 | |
noah metz | 76512afd4e | |
noah metz | 97815c86ff | |
noah metz | 6d6effadec | |
noah metz | e59b4f57fd | |
noah metz | e51e823b19 | |
noah metz | f09a1db2d4 | |
noah metz | 3b35885c90 | |
noah metz | d4fcd80ff8 | |
noah metz | 551370e541 | |
noah metz | 0428645be3 | |
noah metz | 000d369251 | |
noah metz | 76af80e2f8 | |
noah metz | d3f435351c | |
noah metz | 767fc0bd3c | |
noah metz | 34549f471a | |
noah metz | 6bd009b43e | |
noah metz | 6cf2d2d957 | |
noah metz | 230ff2b883 | |
noah metz | 81e49b505b | |
noah metz | 2c1c75572e | |
noah metz | cf248ee5b0 | |
noah metz | d4fb5a0922 | |
noah metz | 7435728321 | |
noah metz | c3058fbd3d | |
noah metz | 61fd7d61aa | |
noah metz | a88c704c57 | |
noah metz | 3cbb6c69e5 | |
noah metz | 99d4f18daf | |
noah metz | e50b550cd7 | |
noah metz | 4dc42a813e | |
noah metz | 2fde6ae282 | |
noah metz | 374fd6e487 | |
noah metz | 6d0925f20f | |
noah metz | 84af718071 | |
noah metz | d227331fe8 | |
noah metz | 372c465472 | |
noah metz | 893fb8c4c4 | |
noah metz | 5d23646cd5 | |
noah metz | ddc3528538 | |
noah metz | a9b40db0de | |
noah metz | 1fbfdf3b8c | |
noah metz | f64455f8ed | |
noah metz | 6c38089aee | |
noah metz | ad407ff183 | |
noah metz | 89f17b1b45 | |
noah metz | e5ba988f01 | |
noah metz | 88d8113b5c | |
noah metz | 7a95af6db2 | |
noah metz | c30b9d082a | |
noah metz | 743569e088 | |
noah metz | fb7fb5938d | |
noah metz | e12d02eb3f | |
noah metz | a9431ecf73 | |
noah metz | 14b084b081 | |
noah metz | 6a0a0762ad | |
noah metz | 7aedf553ee | |
noah metz | 269e7a57e2 | |
noah metz | b846bbb812 | |
noah metz | 5c416a4a3f | |
noah metz | a9d1fe5793 | |
noah metz | 0e2b6ccb2a | |
noah metz | ff46af585d | |
noah metz | a7f721e0cd | |
noah metz | c42ca80d47 | |
noah metz | ce831af290 | |
noah metz | a23dfd2b81 | |
noah metz | dd6b0de414 | |
noah metz | e5c4069cfc | |
noah metz | 81945ab191 | |
noah metz | 543aec054e | |
noah metz | f44752d988 | |
noah metz | fd72ad3901 | |
noah metz | 9485ef9772 | |
noah metz | 53b93d5e70 | |
noah metz | 4b64fb1ef2 | |
noah metz | 5bdc06bf0f | |
noah metz | 64171c6c85 | |
noah metz | 34f8a9f009 | |
noah metz | a05d847863 | |
noah metz | 8a5de1b0de | |
noah metz | 300e735065 | |
noah metz | 8d041fa896 | |
noah metz | 6355cc4226 | |
noah metz | c9d9b9ac03 | |
noah metz | 9b61adc375 | |
noah metz | 06a6b0f09a | |
noah metz | 1585034777 | |
noah metz | ce0634cd61 | |
noah metz | 3ebb6fe223 | |
noah metz | fa22d8f2a9 | |
noah metz | 1c6983ff4a | |
noah metz | 638148afab | |
noah metz | 97c1405e3c | |
noah metz | b7a7d509e6 | |
noah metz | c2d09a07e3 | |
noah metz | 9cb1d26405 | |
noah metz | d2b32bac5e | |
noah metz | 04771b7816 | |
noah metz | 41d88b9d86 | |
noah metz | 84a700909d | |
noah metz | e862f9e49c | |
noah metz | 2c0fced413 | |
noah metz | 82ae5279b0 | |
noah metz | e75171a9c5 | |
noah metz | 308b23ac69 | |
noah metz | 59a9459d00 | |
noah metz | 7944cb694a | |
noah metz | 524717e35e | |
noah metz | 31ecc869ec | |
noah metz | 43dd555801 | |
noah metz | 65c653b896 | |
noah metz | 4db1b6446c | |
noah metz | 5b2b33d930 | |
noah metz | 3e27d1d6b0 | |
noah metz | a696213e38 | |
noah metz | ee98e13044 | |
noah metz | cf11176cff | |
noah metz | ff68f131e5 | |
noah metz | 18703d1a6d | |
noah metz | b174727bda | |
noah metz | 88a55cd095 | |
noah metz | bed500e2db | |
noah metz | 5a694dc067 | |
noah metz | 7b6ceaaad2 | |
noah metz | 1ce98e2719 | |
noah metz | 856867fb10 | |
noah metz | cf8648f615 | |
noah metz | 6c1887ed76 | |
noah metz | 94ef8ca3d0 | |
noah metz | b145148471 | |
noah metz | 583e1957c1 | |
noah metz | 10bd1ee823 | |
noah metz | 62d56f208a | |
noah metz | 4c462a1ec5 | |
noah metz | dc7f742f32 | |
noah metz | 26f57daf23 | |
noah metz | 10ab3a48cf | |
noah metz | bb3c80dbc7 | |
noah metz | 7b84c8bc54 |
@ -0,0 +1,3 @@
|
|||||||
|
[submodule "graphql"]
|
||||||
|
path = graphql
|
||||||
|
url = https://github.com/graphql-go/graphql
|
@ -0,0 +1,662 @@
|
|||||||
|
GNU AFFERO GENERAL PUBLIC LICENSE
|
||||||
|
Version 3, 19 November 2007
|
||||||
|
|
||||||
|
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||||
|
Everyone is permitted to copy and distribute verbatim copies
|
||||||
|
of this license document, but changing it is not allowed.
|
||||||
|
|
||||||
|
Preamble
|
||||||
|
|
||||||
|
The GNU Affero General Public License is a free, copyleft license for
|
||||||
|
software and other kinds of works, specifically designed to ensure
|
||||||
|
cooperation with the community in the case of network server software.
|
||||||
|
|
||||||
|
The licenses for most software and other practical works are designed
|
||||||
|
to take away your freedom to share and change the works. By contrast,
|
||||||
|
our General Public Licenses are 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.
|
||||||
|
|
||||||
|
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.
|
||||||
|
|
||||||
|
Developers that use our General Public Licenses protect your rights
|
||||||
|
with two steps: (1) assert copyright on the software, and (2) offer
|
||||||
|
you this License which gives you legal permission to copy, distribute
|
||||||
|
and/or modify the software.
|
||||||
|
|
||||||
|
A secondary benefit of defending all users' freedom is that
|
||||||
|
improvements made in alternate versions of the program, if they
|
||||||
|
receive widespread use, become available for other developers to
|
||||||
|
incorporate. Many developers of free software are heartened and
|
||||||
|
encouraged by the resulting cooperation. However, in the case of
|
||||||
|
software used on network servers, this result may fail to come about.
|
||||||
|
The GNU General Public License permits making a modified version and
|
||||||
|
letting the public access it on a server without ever releasing its
|
||||||
|
source code to the public.
|
||||||
|
|
||||||
|
The GNU Affero General Public License is designed specifically to
|
||||||
|
ensure that, in such cases, the modified source code becomes available
|
||||||
|
to the community. It requires the operator of a network server to
|
||||||
|
provide the source code of the modified version running there to the
|
||||||
|
users of that server. Therefore, public use of a modified version, on
|
||||||
|
a publicly accessible server, gives the public access to the source
|
||||||
|
code of the modified version.
|
||||||
|
|
||||||
|
An older license, called the Affero General Public License and
|
||||||
|
published by Affero, was designed to accomplish similar goals. This is
|
||||||
|
a different license, not a version of the Affero GPL, but Affero has
|
||||||
|
released a new version of the Affero GPL which permits relicensing under
|
||||||
|
this license.
|
||||||
|
|
||||||
|
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 Affero 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. Remote Network Interaction; Use with the GNU General Public License.
|
||||||
|
|
||||||
|
Notwithstanding any other provision of this License, if you modify the
|
||||||
|
Program, your modified version must prominently offer all users
|
||||||
|
interacting with it remotely through a computer network (if your version
|
||||||
|
supports such interaction) an opportunity to receive the Corresponding
|
||||||
|
Source of your version by providing access to the Corresponding Source
|
||||||
|
from a network server at no charge, through some standard or customary
|
||||||
|
means of facilitating copying of software. This Corresponding Source
|
||||||
|
shall include the Corresponding Source for any work covered by version 3
|
||||||
|
of the GNU General Public License that is incorporated pursuant to the
|
||||||
|
following paragraph.
|
||||||
|
|
||||||
|
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 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 work with which it is combined will remain governed by version
|
||||||
|
3 of the GNU General Public License.
|
||||||
|
|
||||||
|
14. Revised Versions of this License.
|
||||||
|
|
||||||
|
The Free Software Foundation may publish revised and/or new versions of
|
||||||
|
the GNU Affero 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 Affero 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 Affero 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 Affero 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 Affero 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 Affero General Public License for more details.
|
||||||
|
|
||||||
|
You should have received a copy of the GNU Affero General Public License
|
||||||
|
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
|
Also add information on how to contact you by electronic and paper mail.
|
||||||
|
|
||||||
|
If your software can interact with users remotely through a computer
|
||||||
|
network, you should also make sure that it provides a way for users to
|
||||||
|
get its source. For example, if your program is a web application, its
|
||||||
|
interface could display a "Source" link that leads users to an archive
|
||||||
|
of the code. There are many ways you could offer source, and different
|
||||||
|
solutions will be better for different programs; see section 13 for the
|
||||||
|
specific requirements.
|
||||||
|
|
||||||
|
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 AGPL, see
|
||||||
|
<https://www.gnu.org/licenses/>.
|
||||||
|
|
@ -1,16 +1,4 @@
|
|||||||
BINARY_DIR=./bin
|
.PHONY: test
|
||||||
BINARY_NAME=event_managear
|
|
||||||
BINARY_PATH=${BINARY_DIR}/${BINARY_NAME}
|
|
||||||
|
|
||||||
build:
|
|
||||||
go build -o ${BINARY_PATH} event_manager
|
|
||||||
|
|
||||||
clean:
|
|
||||||
rm -rf bin
|
|
||||||
go clean
|
|
||||||
|
|
||||||
run: build
|
|
||||||
${BINARY_PATH}
|
|
||||||
|
|
||||||
test:
|
test:
|
||||||
go test
|
clear && go test
|
||||||
|
@ -0,0 +1,48 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
|
||||||
|
badger "github.com/dgraph-io/badger/v3"
|
||||||
|
gv "github.com/mekkanized/graphvent"
|
||||||
|
)
|
||||||
|
|
||||||
|
func check(err error) {
|
||||||
|
if err != nil {
|
||||||
|
panic(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
db, err := badger.Open(badger.DefaultOptions("").WithInMemory(true))
|
||||||
|
check(err)
|
||||||
|
|
||||||
|
ctx, err := gv.NewContext(&gv.BadgerDB{
|
||||||
|
DB: db,
|
||||||
|
}, gv.NewConsoleLogger([]string{"test"}))
|
||||||
|
check(err)
|
||||||
|
|
||||||
|
gql_ext, err := gv.NewGQLExt(ctx, ":8080", nil, nil)
|
||||||
|
check(err)
|
||||||
|
|
||||||
|
listener_ext := gv.NewListenerExt(1000)
|
||||||
|
|
||||||
|
n1, err := gv.NewNode(ctx, nil, "LockableNode", 1000, gv.NewLockableExt(nil))
|
||||||
|
check(err)
|
||||||
|
|
||||||
|
n2, err := gv.NewNode(ctx, nil, "LockableNode", 1000, gv.NewLockableExt([]gv.NodeID{n1.ID}))
|
||||||
|
check(err)
|
||||||
|
|
||||||
|
n3, err := gv.NewNode(ctx, nil, "LockableNode", 1000, gv.NewLockableExt(nil))
|
||||||
|
check(err)
|
||||||
|
|
||||||
|
_, err = gv.NewNode(ctx, nil, "LockableNode", 1000, gql_ext, listener_ext, gv.NewLockableExt([]gv.NodeID{n2.ID, n3.ID}))
|
||||||
|
check(err)
|
||||||
|
|
||||||
|
for true {
|
||||||
|
select {
|
||||||
|
case message := <- listener_ext.Chan:
|
||||||
|
fmt.Printf("Listener Message: %+v\n", message)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
File diff suppressed because it is too large
Load Diff
@ -0,0 +1,284 @@
|
|||||||
|
package graphvent
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/binary"
|
||||||
|
"fmt"
|
||||||
|
"reflect"
|
||||||
|
"sync"
|
||||||
|
|
||||||
|
badger "github.com/dgraph-io/badger/v3"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Database interface {
|
||||||
|
WriteNodeInit(*Context, *Node) error
|
||||||
|
WriteNodeChanges(*Context, *Node, map[ExtType]Changes) error
|
||||||
|
LoadNode(*Context, NodeID) (*Node, error)
|
||||||
|
}
|
||||||
|
|
||||||
|
const WRITE_BUFFER_SIZE = 1000000
|
||||||
|
type BadgerDB struct {
|
||||||
|
*badger.DB
|
||||||
|
sync.Mutex
|
||||||
|
buffer [WRITE_BUFFER_SIZE]byte
|
||||||
|
}
|
||||||
|
|
||||||
|
func (db *BadgerDB) WriteNodeInit(ctx *Context, node *Node) error {
|
||||||
|
if node == nil {
|
||||||
|
return fmt.Errorf("Cannot serialize nil *Node")
|
||||||
|
}
|
||||||
|
|
||||||
|
return db.Update(func(tx *badger.Txn) error {
|
||||||
|
db.Lock()
|
||||||
|
defer db.Unlock()
|
||||||
|
|
||||||
|
// Get the base key bytes
|
||||||
|
id_ser, err := node.ID.MarshalBinary()
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
cur := 0
|
||||||
|
|
||||||
|
// Write Node value
|
||||||
|
written, err := Serialize(ctx, node, db.buffer[cur:])
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
err = tx.Set(id_ser, db.buffer[cur:cur+written])
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
cur += written
|
||||||
|
|
||||||
|
// Write empty signal queue
|
||||||
|
sigqueue_id := append(id_ser, []byte(" - SIGQUEUE")...)
|
||||||
|
written, err = Serialize(ctx, node.SignalQueue, db.buffer[cur:])
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
err = tx.Set(sigqueue_id, db.buffer[cur:cur+written])
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
cur += written
|
||||||
|
|
||||||
|
// Write node extension list
|
||||||
|
ext_list := []ExtType{}
|
||||||
|
for ext_type := range(node.Extensions) {
|
||||||
|
ext_list = append(ext_list, ext_type)
|
||||||
|
}
|
||||||
|
written, err = Serialize(ctx, ext_list, db.buffer[cur:])
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
ext_list_id := append(id_ser, []byte(" - EXTLIST")...)
|
||||||
|
err = tx.Set(ext_list_id, db.buffer[cur:cur+written])
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
cur += written
|
||||||
|
|
||||||
|
// For each extension:
|
||||||
|
for ext_type, ext := range(node.Extensions) {
|
||||||
|
ext_info, exists := ctx.Extensions[ext_type]
|
||||||
|
if exists == false {
|
||||||
|
return fmt.Errorf("Cannot serialize node with unknown extension %s", reflect.TypeOf(ext))
|
||||||
|
}
|
||||||
|
|
||||||
|
ext_value := reflect.ValueOf(ext).Elem()
|
||||||
|
ext_id := binary.BigEndian.AppendUint64(id_ser, uint64(ext_type))
|
||||||
|
|
||||||
|
// Write each field to a seperate key
|
||||||
|
for field_tag, field_info := range(ext_info.Fields) {
|
||||||
|
field_value := ext_value.FieldByIndex(field_info.Index)
|
||||||
|
|
||||||
|
field_id := make([]byte, len(ext_id) + 8)
|
||||||
|
tmp := binary.BigEndian.AppendUint64(ext_id, uint64(GetFieldTag(string(field_tag))))
|
||||||
|
copy(field_id, tmp)
|
||||||
|
|
||||||
|
written, err := SerializeValue(ctx, field_value, db.buffer[cur:])
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("Extension serialize err: %s, %w", reflect.TypeOf(ext), err)
|
||||||
|
}
|
||||||
|
|
||||||
|
err = tx.Set(field_id, db.buffer[cur:cur+written])
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("Extension set err: %s, %w", reflect.TypeOf(ext), err)
|
||||||
|
}
|
||||||
|
cur += written
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (db *BadgerDB) WriteNodeChanges(ctx *Context, node *Node, changes map[ExtType]Changes) error {
|
||||||
|
return db.Update(func(tx *badger.Txn) error {
|
||||||
|
db.Lock()
|
||||||
|
defer db.Unlock()
|
||||||
|
|
||||||
|
// Get the base key bytes
|
||||||
|
id_bytes := ([16]byte)(node.ID)
|
||||||
|
|
||||||
|
cur := 0
|
||||||
|
|
||||||
|
// Write the signal queue if it needs to be written
|
||||||
|
if node.writeSignalQueue {
|
||||||
|
node.writeSignalQueue = false
|
||||||
|
|
||||||
|
sigqueue_id := append(id_bytes[:], []byte(" - SIGQUEUE")...)
|
||||||
|
written, err := Serialize(ctx, node.SignalQueue, db.buffer[cur:])
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("SignalQueue Serialize Error: %+v, %w", node.SignalQueue, err)
|
||||||
|
}
|
||||||
|
err = tx.Set(sigqueue_id, db.buffer[cur:cur+written])
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("SignalQueue set error: %+v, %w", node.SignalQueue, err)
|
||||||
|
}
|
||||||
|
cur += written
|
||||||
|
}
|
||||||
|
|
||||||
|
// For each ext in changes
|
||||||
|
for ext_type, changes := range(changes) {
|
||||||
|
ext_info, exists := ctx.Extensions[ext_type]
|
||||||
|
if exists == false {
|
||||||
|
return fmt.Errorf("%s is not an extension in ctx", ext_type)
|
||||||
|
}
|
||||||
|
|
||||||
|
ext, exists := node.Extensions[ext_type]
|
||||||
|
if exists == false {
|
||||||
|
return fmt.Errorf("%s is not an extension in %s", ext_type, node.ID)
|
||||||
|
}
|
||||||
|
ext_id := binary.BigEndian.AppendUint64(id_bytes[:], uint64(ext_type))
|
||||||
|
ext_value := reflect.ValueOf(ext)
|
||||||
|
|
||||||
|
// Write each field
|
||||||
|
for _, tag := range(changes) {
|
||||||
|
field_info, exists := ext_info.Fields[tag]
|
||||||
|
if exists == false {
|
||||||
|
return fmt.Errorf("Cannot serialize field %s of extension %s, does not exist", tag, ext_type)
|
||||||
|
}
|
||||||
|
|
||||||
|
field_value := ext_value.FieldByIndex(field_info.Index)
|
||||||
|
|
||||||
|
field_id := make([]byte, len(ext_id) + 8)
|
||||||
|
tmp := binary.BigEndian.AppendUint64(ext_id, uint64(GetFieldTag(string(tag))))
|
||||||
|
copy(field_id, tmp)
|
||||||
|
|
||||||
|
written, err := SerializeValue(ctx, field_value, db.buffer[cur:])
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("Extension serialize err: %s, %w", reflect.TypeOf(ext), err)
|
||||||
|
}
|
||||||
|
|
||||||
|
err = tx.Set(field_id, db.buffer[cur:cur+written])
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("Extension set err: %s, %w", reflect.TypeOf(ext), err)
|
||||||
|
}
|
||||||
|
cur += written
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (db *BadgerDB) LoadNode(ctx *Context, id NodeID) (*Node, error) {
|
||||||
|
var node *Node = nil
|
||||||
|
|
||||||
|
err := db.View(func(tx *badger.Txn) error {
|
||||||
|
// Get the base key bytes
|
||||||
|
id_ser, err := id.MarshalBinary()
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("Failed to serialize node_id: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get the node value
|
||||||
|
node_item, err := tx.Get(id_ser)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("Failed to get node_item: %w", NodeNotFoundError)
|
||||||
|
}
|
||||||
|
|
||||||
|
err = node_item.Value(func(val []byte) error {
|
||||||
|
ctx.Log.Logf("db", "DESERIALIZE_NODE(%d bytes): %+v", len(val), val)
|
||||||
|
node, err = Deserialize[*Node](ctx, val)
|
||||||
|
return err
|
||||||
|
})
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("Failed to deserialize Node %s - %w", id, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get the signal queue
|
||||||
|
sigqueue_id := append(id_ser, []byte(" - SIGQUEUE")...)
|
||||||
|
sigqueue_item, err := tx.Get(sigqueue_id)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("Failed to get sigqueue_id: %w", err)
|
||||||
|
}
|
||||||
|
err = sigqueue_item.Value(func(val []byte) error {
|
||||||
|
node.SignalQueue, err = Deserialize[[]QueuedSignal](ctx, val)
|
||||||
|
return err
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("Failed to deserialize []QueuedSignal for %s: %w", id, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get the extension list
|
||||||
|
ext_list_id := append(id_ser, []byte(" - EXTLIST")...)
|
||||||
|
ext_list_item, err := tx.Get(ext_list_id)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
var ext_list []ExtType
|
||||||
|
ext_list_item.Value(func(val []byte) error {
|
||||||
|
ext_list, err = Deserialize[[]ExtType](ctx, val)
|
||||||
|
return err
|
||||||
|
})
|
||||||
|
|
||||||
|
// Get the extensions
|
||||||
|
for _, ext_type := range(ext_list) {
|
||||||
|
ext_id := binary.BigEndian.AppendUint64(id_ser, uint64(ext_type))
|
||||||
|
ext_info, exists := ctx.Extensions[ext_type]
|
||||||
|
if exists == false {
|
||||||
|
return fmt.Errorf("Extension %s not in context", ext_type)
|
||||||
|
}
|
||||||
|
|
||||||
|
ext := reflect.New(ext_info.Type)
|
||||||
|
for field_tag, field_info := range(ext_info.Fields) {
|
||||||
|
field_id := binary.BigEndian.AppendUint64(ext_id, uint64(GetFieldTag(string(field_tag))))
|
||||||
|
field_item, err := tx.Get(field_id)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("Failed to find key for %s:%s(%x) - %w", ext_type, field_tag, field_id, err)
|
||||||
|
}
|
||||||
|
err = field_item.Value(func(val []byte) error {
|
||||||
|
value, _, err := DeserializeValue(ctx, val, field_info.Type)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
ext.Elem().FieldByIndex(field_info.Index).Set(value)
|
||||||
|
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
node.Extensions[ext_type] = ext.Interface().(Extension)
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
} else if node == nil {
|
||||||
|
return nil, fmt.Errorf("Tried to return nil *Node from BadgerDB.LoadNode without error")
|
||||||
|
}
|
||||||
|
|
||||||
|
return node, nil
|
||||||
|
}
|
@ -0,0 +1,16 @@
|
|||||||
|
package graphvent
|
||||||
|
|
||||||
|
type Tag string
|
||||||
|
type Changes []Tag
|
||||||
|
|
||||||
|
// Extensions are data attached to nodes that process signals
|
||||||
|
type Extension interface {
|
||||||
|
// Called to process incoming signals, returning changes and messages to send
|
||||||
|
Process(*Context, *Node, NodeID, Signal) ([]Message, Changes)
|
||||||
|
|
||||||
|
// Called when the node is loaded into a context(creation or move), so extension data can be initialized
|
||||||
|
Load(*Context, *Node) error
|
||||||
|
|
||||||
|
// Called when the node is unloaded from a context(deletion or move), so extension data can be cleaned up
|
||||||
|
Unload(*Context, *Node)
|
||||||
|
}
|
@ -1,32 +1,36 @@
|
|||||||
module github.com/mekkanized/graphvent
|
module github.com/mekkanized/graphvent
|
||||||
|
|
||||||
go 1.20
|
go 1.22.0
|
||||||
|
|
||||||
require (
|
require (
|
||||||
|
github.com/dgraph-io/badger/v3 v3.2103.5
|
||||||
|
github.com/gobwas/ws v1.2.1
|
||||||
|
github.com/google/uuid v1.3.0
|
||||||
|
github.com/graphql-go/graphql v0.8.1
|
||||||
|
github.com/rs/zerolog v1.29.1
|
||||||
|
golang.org/x/net v0.7.0
|
||||||
|
)
|
||||||
|
|
||||||
|
require (
|
||||||
|
filippo.io/edwards25519 v1.0.0 // indirect
|
||||||
github.com/cespare/xxhash v1.1.0 // indirect
|
github.com/cespare/xxhash v1.1.0 // indirect
|
||||||
github.com/cespare/xxhash/v2 v2.1.2 // indirect
|
github.com/cespare/xxhash/v2 v2.1.2 // indirect
|
||||||
github.com/dgraph-io/badger/v3 v3.2103.5 // indirect
|
|
||||||
github.com/dgraph-io/badger/v4 v4.1.0 // indirect
|
|
||||||
github.com/dgraph-io/ristretto v0.1.1 // indirect
|
github.com/dgraph-io/ristretto v0.1.1 // indirect
|
||||||
github.com/dustin/go-humanize v1.0.0 // indirect
|
github.com/dustin/go-humanize v1.0.0 // indirect
|
||||||
github.com/gobwas/httphead v0.1.0 // indirect
|
github.com/gobwas/httphead v0.1.0 // indirect
|
||||||
github.com/gobwas/pool v0.2.1 // indirect
|
github.com/gobwas/pool v0.2.1 // indirect
|
||||||
github.com/gobwas/ws v1.2.1 // indirect
|
|
||||||
github.com/gogo/protobuf v1.3.2 // indirect
|
github.com/gogo/protobuf v1.3.2 // indirect
|
||||||
github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b // indirect
|
github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b // indirect
|
||||||
github.com/golang/groupcache v0.0.0-20190702054246-869f871628b6 // indirect
|
github.com/golang/groupcache v0.0.0-20190702054246-869f871628b6 // indirect
|
||||||
github.com/golang/protobuf v1.3.1 // indirect
|
github.com/golang/protobuf v1.3.1 // indirect
|
||||||
github.com/golang/snappy v0.0.3 // indirect
|
github.com/golang/snappy v0.0.3 // indirect
|
||||||
github.com/google/flatbuffers v1.12.1 // indirect
|
github.com/google/flatbuffers v1.12.1 // indirect
|
||||||
github.com/google/uuid v1.3.0 // indirect
|
|
||||||
github.com/graphql-go/graphql v0.8.1 // indirect
|
|
||||||
github.com/graphql-go/handler v0.2.3 // indirect
|
|
||||||
github.com/klauspost/compress v1.12.3 // indirect
|
github.com/klauspost/compress v1.12.3 // indirect
|
||||||
github.com/mattn/go-colorable v0.1.12 // indirect
|
github.com/mattn/go-colorable v0.1.12 // indirect
|
||||||
github.com/mattn/go-isatty v0.0.14 // indirect
|
github.com/mattn/go-isatty v0.0.14 // indirect
|
||||||
github.com/pkg/errors v0.9.1 // indirect
|
github.com/pkg/errors v0.9.1 // indirect
|
||||||
github.com/rs/zerolog v1.29.1 // indirect
|
github.com/stretchr/testify v1.8.2 // indirect
|
||||||
go.opencensus.io v0.22.5 // indirect
|
go.opencensus.io v0.22.5 // indirect
|
||||||
golang.org/x/net v0.7.0 // indirect
|
golang.org/x/exp v0.0.0-20240222234643-814bf88cf225 // indirect
|
||||||
golang.org/x/sys v0.6.0 // indirect
|
golang.org/x/sys v0.13.0 // indirect
|
||||||
)
|
)
|
||||||
|
@ -1,812 +0,0 @@
|
|||||||
package graphvent
|
|
||||||
|
|
||||||
import (
|
|
||||||
"github.com/graphql-go/graphql"
|
|
||||||
"reflect"
|
|
||||||
"fmt"
|
|
||||||
"time"
|
|
||||||
)
|
|
||||||
|
|
||||||
var gql_interface_graph_node *graphql.Interface = nil
|
|
||||||
func GQLInterfaceGraphNode() *graphql.Interface {
|
|
||||||
if gql_interface_graph_node == nil {
|
|
||||||
gql_interface_graph_node = graphql.NewInterface(graphql.InterfaceConfig{
|
|
||||||
Name: "GraphNode",
|
|
||||||
ResolveType: func(p graphql.ResolveTypeParams) *graphql.Object {
|
|
||||||
valid_nodes, ok := p.Context.Value("valid_nodes").(map[reflect.Type]*graphql.Object)
|
|
||||||
if ok == false {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
for key, value := range(valid_nodes) {
|
|
||||||
if reflect.TypeOf(p.Value) == key {
|
|
||||||
return value
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
},
|
|
||||||
Fields: graphql.Fields{},
|
|
||||||
})
|
|
||||||
|
|
||||||
gql_interface_graph_node.AddFieldConfig("ID", &graphql.Field{
|
|
||||||
Type: graphql.String,
|
|
||||||
})
|
|
||||||
|
|
||||||
gql_interface_graph_node.AddFieldConfig("Name", &graphql.Field{
|
|
||||||
Type: graphql.String,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
return gql_interface_graph_node
|
|
||||||
}
|
|
||||||
|
|
||||||
var gql_list_thread *graphql.List = nil
|
|
||||||
func GQLListThread() *graphql.List {
|
|
||||||
if gql_list_thread == nil {
|
|
||||||
gql_list_thread = graphql.NewList(GQLInterfaceThread())
|
|
||||||
}
|
|
||||||
return gql_list_thread
|
|
||||||
}
|
|
||||||
|
|
||||||
var gql_interface_thread *graphql.Interface = nil
|
|
||||||
func GQLInterfaceThread() *graphql.Interface {
|
|
||||||
if gql_interface_thread == nil {
|
|
||||||
gql_interface_thread = graphql.NewInterface(graphql.InterfaceConfig{
|
|
||||||
Name: "Thread",
|
|
||||||
ResolveType: func(p graphql.ResolveTypeParams) *graphql.Object {
|
|
||||||
valid_nodes, ok := p.Context.Value("valid_threads").(map[reflect.Type]*graphql.Object)
|
|
||||||
if ok == false {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
for key, value := range(valid_nodes) {
|
|
||||||
if reflect.TypeOf(p.Value) == key {
|
|
||||||
return value
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
},
|
|
||||||
Fields: graphql.Fields{},
|
|
||||||
})
|
|
||||||
|
|
||||||
gql_interface_thread.AddFieldConfig("ID", &graphql.Field{
|
|
||||||
Type: graphql.String,
|
|
||||||
})
|
|
||||||
|
|
||||||
gql_interface_thread.AddFieldConfig("Name", &graphql.Field{
|
|
||||||
Type: graphql.String,
|
|
||||||
})
|
|
||||||
|
|
||||||
gql_interface_thread.AddFieldConfig("Children", &graphql.Field{
|
|
||||||
Type: GQLListThread(),
|
|
||||||
})
|
|
||||||
|
|
||||||
gql_interface_thread.AddFieldConfig("Parent", &graphql.Field{
|
|
||||||
Type: GQLInterfaceThread(),
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
return gql_interface_thread
|
|
||||||
}
|
|
||||||
|
|
||||||
var gql_list_lockable *graphql.List = nil
|
|
||||||
func GQLListLockable() *graphql.List {
|
|
||||||
if gql_list_lockable == nil {
|
|
||||||
gql_list_lockable = graphql.NewList(GQLInterfaceLockable())
|
|
||||||
}
|
|
||||||
return gql_list_lockable
|
|
||||||
}
|
|
||||||
|
|
||||||
var gql_interface_lockable *graphql.Interface = nil
|
|
||||||
func GQLInterfaceLockable() *graphql.Interface {
|
|
||||||
if gql_interface_lockable == nil {
|
|
||||||
gql_interface_lockable = graphql.NewInterface(graphql.InterfaceConfig{
|
|
||||||
Name: "Lockable",
|
|
||||||
ResolveType: func(p graphql.ResolveTypeParams) *graphql.Object {
|
|
||||||
valid_nodes, ok := p.Context.Value("valid_lockables").(map[reflect.Type]*graphql.Object)
|
|
||||||
if ok == false {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
for key, value := range(valid_nodes) {
|
|
||||||
if reflect.TypeOf(p.Value) == key {
|
|
||||||
return value
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
},
|
|
||||||
Fields: graphql.Fields{},
|
|
||||||
})
|
|
||||||
|
|
||||||
gql_interface_lockable.AddFieldConfig("ID", &graphql.Field{
|
|
||||||
Type: graphql.String,
|
|
||||||
})
|
|
||||||
|
|
||||||
gql_interface_lockable.AddFieldConfig("Name", &graphql.Field{
|
|
||||||
Type: graphql.String,
|
|
||||||
})
|
|
||||||
|
|
||||||
if gql_list_lockable == nil {
|
|
||||||
gql_list_lockable = graphql.NewList(gql_interface_lockable)
|
|
||||||
}
|
|
||||||
|
|
||||||
gql_interface_lockable.AddFieldConfig("Requirements", &graphql.Field{
|
|
||||||
Type: GQLListLockable(),
|
|
||||||
})
|
|
||||||
|
|
||||||
gql_interface_lockable.AddFieldConfig("Dependencies", &graphql.Field{
|
|
||||||
Type: GQLListLockable(),
|
|
||||||
})
|
|
||||||
|
|
||||||
gql_interface_lockable.AddFieldConfig("Owner", &graphql.Field{
|
|
||||||
Type: GQLInterfaceLockable(),
|
|
||||||
})
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
return gql_interface_lockable
|
|
||||||
}
|
|
||||||
|
|
||||||
func GQLNodeID(p graphql.ResolveParams) (interface{}, error) {
|
|
||||||
node, ok := p.Source.(GraphNode)
|
|
||||||
if ok == false || node == nil {
|
|
||||||
return nil, fmt.Errorf("Failed to cast source to GraphNode")
|
|
||||||
}
|
|
||||||
return node.ID(), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func GQLNodeName(p graphql.ResolveParams) (interface{}, error) {
|
|
||||||
node, ok := p.Source.(GraphNode)
|
|
||||||
if ok == false || node == nil {
|
|
||||||
return nil, fmt.Errorf("Failed to cast source to GraphNode")
|
|
||||||
}
|
|
||||||
|
|
||||||
ctx, ok := p.Context.Value("graph_context").(*GraphContext)
|
|
||||||
if ok == false {
|
|
||||||
return nil, fmt.Errorf("Failed to cast context graph_context to GraphContext")
|
|
||||||
}
|
|
||||||
|
|
||||||
name, err := UseStates(ctx, []GraphNode{node}, func(states []NodeState) (interface{}, error) {
|
|
||||||
return states[0].Name(), nil
|
|
||||||
})
|
|
||||||
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
name_str, ok := name.(string)
|
|
||||||
if ok == false {
|
|
||||||
return nil, fmt.Errorf("Failed to cast name to string %+v", name)
|
|
||||||
}
|
|
||||||
|
|
||||||
return name_str, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func GQLThreadListen(p graphql.ResolveParams) (interface{}, error) {
|
|
||||||
node, ok := p.Source.(*GQLThread)
|
|
||||||
if ok == false || node == nil {
|
|
||||||
return nil, fmt.Errorf("Failed to cast source to GQLThread")
|
|
||||||
}
|
|
||||||
|
|
||||||
ctx, ok := p.Context.Value("graph_context").(*GraphContext)
|
|
||||||
if ok == false {
|
|
||||||
return nil, fmt.Errorf("Failed to cast context graph_context to GraphContext")
|
|
||||||
}
|
|
||||||
|
|
||||||
listen, err := UseStates(ctx, []GraphNode{node}, func(states []NodeState) (interface{}, error) {
|
|
||||||
gql_thread, ok := states[0].(*GQLThreadState)
|
|
||||||
if ok == false {
|
|
||||||
return nil, fmt.Errorf("Failed to cast state to GQLThreadState")
|
|
||||||
}
|
|
||||||
return gql_thread.Listen, nil
|
|
||||||
})
|
|
||||||
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
listen_str, ok := listen.(string)
|
|
||||||
if ok == false {
|
|
||||||
return nil, fmt.Errorf("Failed to cast listen to string %+v", listen)
|
|
||||||
}
|
|
||||||
|
|
||||||
return listen_str, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func GQLThreadParent(p graphql.ResolveParams) (interface{}, error) {
|
|
||||||
node, ok := p.Source.(Thread)
|
|
||||||
if ok == false || node == nil {
|
|
||||||
return nil, fmt.Errorf("Failed to cast source to Thread")
|
|
||||||
}
|
|
||||||
|
|
||||||
ctx, ok := p.Context.Value("graph_context").(*GraphContext)
|
|
||||||
if ok == false {
|
|
||||||
return nil, fmt.Errorf("Failed to cast context graph_context to GraphContext")
|
|
||||||
}
|
|
||||||
|
|
||||||
parent, err := UseStates(ctx, []GraphNode{node}, func(states []NodeState) (interface{}, error) {
|
|
||||||
gql_thread, ok := states[0].(ThreadState)
|
|
||||||
if ok == false {
|
|
||||||
return nil, fmt.Errorf("Failed to cast state to ThreadState")
|
|
||||||
}
|
|
||||||
return gql_thread.Parent(), nil
|
|
||||||
})
|
|
||||||
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
parent_node, ok := parent.(Thread)
|
|
||||||
if ok == false {
|
|
||||||
return nil, fmt.Errorf("Failed to cast parent to node %+v", parent)
|
|
||||||
}
|
|
||||||
|
|
||||||
return parent_node, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func GQLThreadChildren(p graphql.ResolveParams) (interface{}, error) {
|
|
||||||
node, ok := p.Source.(Thread)
|
|
||||||
if ok == false || node == nil {
|
|
||||||
return nil, fmt.Errorf("Failed to cast source to Thread")
|
|
||||||
}
|
|
||||||
|
|
||||||
ctx, ok := p.Context.Value("graph_context").(*GraphContext)
|
|
||||||
if ok == false {
|
|
||||||
return nil, fmt.Errorf("Failed to cast context graph_context to GraphContext")
|
|
||||||
}
|
|
||||||
|
|
||||||
children, err := UseStates(ctx, []GraphNode{node}, func(states []NodeState) (interface{}, error) {
|
|
||||||
gql_thread, ok := states[0].(ThreadState)
|
|
||||||
if ok == false {
|
|
||||||
return nil, fmt.Errorf("Failed to cast state to ThreadState")
|
|
||||||
}
|
|
||||||
return gql_thread.Children(), nil
|
|
||||||
})
|
|
||||||
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
children_nodes, ok := children.([]Thread)
|
|
||||||
if ok == false {
|
|
||||||
return nil, fmt.Errorf("Failed to cast children to threads %+v", children)
|
|
||||||
}
|
|
||||||
|
|
||||||
return children_nodes, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func GQLLockableRequirements(p graphql.ResolveParams) (interface{}, error) {
|
|
||||||
node, ok := p.Source.(Lockable)
|
|
||||||
if ok == false || node == nil {
|
|
||||||
return nil, fmt.Errorf("Failed to cast source to Lockable")
|
|
||||||
}
|
|
||||||
|
|
||||||
ctx, ok := p.Context.Value("graph_context").(*GraphContext)
|
|
||||||
if ok == false {
|
|
||||||
return nil, fmt.Errorf("Failed to cast context graph_context to GraphContext")
|
|
||||||
}
|
|
||||||
|
|
||||||
requirements, err := UseStates(ctx, []GraphNode{node}, func(states []NodeState) (interface{}, error) {
|
|
||||||
gql_thread, ok := states[0].(LockableState)
|
|
||||||
if ok == false {
|
|
||||||
return nil, fmt.Errorf("Failed to cast state to LockableState")
|
|
||||||
}
|
|
||||||
return gql_thread.Requirements(), nil
|
|
||||||
})
|
|
||||||
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
requirement_nodes, ok := requirements.([]Lockable)
|
|
||||||
if ok == false {
|
|
||||||
return nil, fmt.Errorf("Failed to cast requirements to lockables %+v", requirements)
|
|
||||||
}
|
|
||||||
|
|
||||||
return requirement_nodes, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func GQLLockableDependencies(p graphql.ResolveParams) (interface{}, error) {
|
|
||||||
node, ok := p.Source.(Lockable)
|
|
||||||
if ok == false || node == nil {
|
|
||||||
return nil, fmt.Errorf("Failed to cast source to Lockable")
|
|
||||||
}
|
|
||||||
|
|
||||||
ctx, ok := p.Context.Value("graph_context").(*GraphContext)
|
|
||||||
if ok == false {
|
|
||||||
return nil, fmt.Errorf("Failed to cast context graph_context to GraphContext")
|
|
||||||
}
|
|
||||||
|
|
||||||
dependencies, err := UseStates(ctx, []GraphNode{node}, func(states []NodeState) (interface{}, error) {
|
|
||||||
gql_thread, ok := states[0].(LockableState)
|
|
||||||
if ok == false {
|
|
||||||
return nil, fmt.Errorf("Failed to cast state to LockableState")
|
|
||||||
}
|
|
||||||
return gql_thread.Dependencies(), nil
|
|
||||||
})
|
|
||||||
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
dependency_nodes, ok := dependencies.([]Lockable)
|
|
||||||
if ok == false {
|
|
||||||
return nil, fmt.Errorf("Failed to cast dependencies to lockables %+v", dependencies)
|
|
||||||
}
|
|
||||||
|
|
||||||
return dependency_nodes, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func GQLLockableOwner(p graphql.ResolveParams) (interface{}, error) {
|
|
||||||
node, ok := p.Source.(Lockable)
|
|
||||||
if ok == false || node == nil {
|
|
||||||
return nil, fmt.Errorf("Failed to cast source to Lockable")
|
|
||||||
}
|
|
||||||
|
|
||||||
ctx, ok := p.Context.Value("graph_context").(*GraphContext)
|
|
||||||
if ok == false {
|
|
||||||
return nil, fmt.Errorf("Failed to cast context graph_context to GraphContext")
|
|
||||||
}
|
|
||||||
|
|
||||||
owner, err := UseStates(ctx, []GraphNode{node}, func(states []NodeState) (interface{}, error) {
|
|
||||||
gql_thread, ok := states[0].(LockableState)
|
|
||||||
if ok == false {
|
|
||||||
return nil, fmt.Errorf("Failed to cast state to LockableState")
|
|
||||||
}
|
|
||||||
return gql_thread.Owner(), nil
|
|
||||||
})
|
|
||||||
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
// TODO actually cast to LockHolder and add gql interface for it
|
|
||||||
owner_node, ok := owner.(Lockable)
|
|
||||||
if ok == false {
|
|
||||||
return nil, fmt.Errorf("Failed to cast owner to Lockable %+v", owner)
|
|
||||||
}
|
|
||||||
|
|
||||||
return owner_node, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
var gql_type_gql_thread *graphql.Object = nil
|
|
||||||
func GQLTypeGQLThread() * graphql.Object {
|
|
||||||
if gql_type_gql_thread == nil {
|
|
||||||
gql_type_gql_thread = graphql.NewObject(graphql.ObjectConfig{
|
|
||||||
Name: "GQLThread",
|
|
||||||
Interfaces: []*graphql.Interface{
|
|
||||||
GQLInterfaceGraphNode(),
|
|
||||||
GQLInterfaceThread(),
|
|
||||||
GQLInterfaceLockable(),
|
|
||||||
},
|
|
||||||
IsTypeOf: func(p graphql.IsTypeOfParams) bool {
|
|
||||||
_, ok := p.Value.(*GQLThread)
|
|
||||||
return ok
|
|
||||||
},
|
|
||||||
Fields: graphql.Fields{},
|
|
||||||
})
|
|
||||||
|
|
||||||
gql_type_gql_thread.AddFieldConfig("ID", &graphql.Field{
|
|
||||||
Type: graphql.String,
|
|
||||||
Resolve: GQLNodeID,
|
|
||||||
})
|
|
||||||
|
|
||||||
gql_type_gql_thread.AddFieldConfig("Name", &graphql.Field{
|
|
||||||
Type: graphql.String,
|
|
||||||
Resolve: GQLNodeName,
|
|
||||||
})
|
|
||||||
|
|
||||||
gql_type_gql_thread.AddFieldConfig("Children", &graphql.Field{
|
|
||||||
Type: GQLListThread(),
|
|
||||||
Resolve: GQLThreadChildren,
|
|
||||||
})
|
|
||||||
|
|
||||||
gql_type_gql_thread.AddFieldConfig("Parent", &graphql.Field{
|
|
||||||
Type: GQLInterfaceThread(),
|
|
||||||
Resolve: GQLThreadParent,
|
|
||||||
})
|
|
||||||
|
|
||||||
gql_type_gql_thread.AddFieldConfig("Listen", &graphql.Field{
|
|
||||||
Type: graphql.String,
|
|
||||||
Resolve: GQLThreadListen,
|
|
||||||
})
|
|
||||||
|
|
||||||
gql_type_gql_thread.AddFieldConfig("Requirements", &graphql.Field{
|
|
||||||
Type: GQLListLockable(),
|
|
||||||
Resolve: GQLLockableRequirements,
|
|
||||||
})
|
|
||||||
|
|
||||||
gql_type_gql_thread.AddFieldConfig("Owner", &graphql.Field{
|
|
||||||
Type: GQLInterfaceLockable(),
|
|
||||||
Resolve: GQLLockableOwner,
|
|
||||||
})
|
|
||||||
|
|
||||||
gql_type_gql_thread.AddFieldConfig("Dependencies", &graphql.Field{
|
|
||||||
Type: GQLListLockable(),
|
|
||||||
Resolve: GQLLockableDependencies,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
return gql_type_gql_thread
|
|
||||||
}
|
|
||||||
|
|
||||||
var gql_type_base_thread *graphql.Object = nil
|
|
||||||
func GQLTypeBaseThread() * graphql.Object {
|
|
||||||
if gql_type_base_thread == nil {
|
|
||||||
gql_type_base_thread = graphql.NewObject(graphql.ObjectConfig{
|
|
||||||
Name: "BaseThread",
|
|
||||||
Interfaces: []*graphql.Interface{
|
|
||||||
GQLInterfaceGraphNode(),
|
|
||||||
GQLInterfaceThread(),
|
|
||||||
GQLInterfaceLockable(),
|
|
||||||
},
|
|
||||||
IsTypeOf: func(p graphql.IsTypeOfParams) bool {
|
|
||||||
valid_threads, ok := p.Context.Value("valid_threads").(map[reflect.Type]*graphql.Object)
|
|
||||||
if ok == false {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
value_type := reflect.TypeOf(p.Value)
|
|
||||||
for go_type, _ := range(valid_threads) {
|
|
||||||
if value_type == go_type {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return false
|
|
||||||
},
|
|
||||||
Fields: graphql.Fields{},
|
|
||||||
})
|
|
||||||
gql_type_base_thread.AddFieldConfig("ID", &graphql.Field{
|
|
||||||
Type: graphql.String,
|
|
||||||
Resolve: GQLNodeID,
|
|
||||||
})
|
|
||||||
|
|
||||||
gql_type_base_thread.AddFieldConfig("Name", &graphql.Field{
|
|
||||||
Type: graphql.String,
|
|
||||||
Resolve: GQLNodeName,
|
|
||||||
})
|
|
||||||
|
|
||||||
gql_type_base_thread.AddFieldConfig("Children", &graphql.Field{
|
|
||||||
Type: GQLListThread(),
|
|
||||||
Resolve: GQLThreadChildren,
|
|
||||||
})
|
|
||||||
|
|
||||||
gql_type_base_thread.AddFieldConfig("Parent", &graphql.Field{
|
|
||||||
Type: GQLInterfaceThread(),
|
|
||||||
Resolve: GQLThreadParent,
|
|
||||||
})
|
|
||||||
|
|
||||||
gql_type_base_thread.AddFieldConfig("Requirements", &graphql.Field{
|
|
||||||
Type: GQLListLockable(),
|
|
||||||
Resolve: GQLLockableRequirements,
|
|
||||||
})
|
|
||||||
|
|
||||||
gql_type_base_thread.AddFieldConfig("Owner", &graphql.Field{
|
|
||||||
Type: GQLInterfaceLockable(),
|
|
||||||
Resolve: GQLLockableOwner,
|
|
||||||
})
|
|
||||||
|
|
||||||
gql_type_base_thread.AddFieldConfig("Dependencies", &graphql.Field{
|
|
||||||
Type: GQLListLockable(),
|
|
||||||
Resolve: GQLLockableDependencies,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
return gql_type_base_thread
|
|
||||||
}
|
|
||||||
|
|
||||||
var gql_type_base_lockable *graphql.Object = nil
|
|
||||||
func GQLTypeBaseLockable() * graphql.Object {
|
|
||||||
if gql_type_base_lockable == nil {
|
|
||||||
gql_type_base_lockable = graphql.NewObject(graphql.ObjectConfig{
|
|
||||||
Name: "BaseLockable",
|
|
||||||
Interfaces: []*graphql.Interface{
|
|
||||||
GQLInterfaceGraphNode(),
|
|
||||||
GQLInterfaceLockable(),
|
|
||||||
},
|
|
||||||
IsTypeOf: func(p graphql.IsTypeOfParams) bool {
|
|
||||||
valid_lockables, ok := p.Context.Value("valid_lockables").(map[reflect.Type]*graphql.Object)
|
|
||||||
if ok == false {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
value_type := reflect.TypeOf(p.Value)
|
|
||||||
for go_type, _ := range(valid_lockables) {
|
|
||||||
if value_type == go_type {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return false
|
|
||||||
},
|
|
||||||
Fields: graphql.Fields{},
|
|
||||||
})
|
|
||||||
|
|
||||||
gql_type_base_lockable.AddFieldConfig("ID", &graphql.Field{
|
|
||||||
Type: graphql.String,
|
|
||||||
Resolve: GQLNodeID,
|
|
||||||
})
|
|
||||||
|
|
||||||
gql_type_base_lockable.AddFieldConfig("Name", &graphql.Field{
|
|
||||||
Type: graphql.String,
|
|
||||||
Resolve: GQLNodeName,
|
|
||||||
})
|
|
||||||
|
|
||||||
gql_type_base_lockable.AddFieldConfig("Requirements", &graphql.Field{
|
|
||||||
Type: GQLListLockable(),
|
|
||||||
Resolve: GQLLockableRequirements,
|
|
||||||
})
|
|
||||||
|
|
||||||
gql_type_base_lockable.AddFieldConfig("Owner", &graphql.Field{
|
|
||||||
Type: GQLInterfaceLockable(),
|
|
||||||
Resolve: GQLLockableOwner,
|
|
||||||
})
|
|
||||||
|
|
||||||
gql_type_base_lockable.AddFieldConfig("Dependencies", &graphql.Field{
|
|
||||||
Type: GQLListLockable(),
|
|
||||||
Resolve: GQLLockableDependencies,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
return gql_type_base_lockable
|
|
||||||
}
|
|
||||||
|
|
||||||
var gql_type_base_node *graphql.Object = nil
|
|
||||||
func GQLTypeBaseNode() * graphql.Object {
|
|
||||||
if gql_type_base_node == nil {
|
|
||||||
gql_type_base_node = graphql.NewObject(graphql.ObjectConfig{
|
|
||||||
Name: "BaseNode",
|
|
||||||
Interfaces: []*graphql.Interface{
|
|
||||||
GQLInterfaceGraphNode(),
|
|
||||||
},
|
|
||||||
IsTypeOf: func(p graphql.IsTypeOfParams) bool {
|
|
||||||
valid_nodes, ok := p.Context.Value("valid_nodes").(map[reflect.Type]*graphql.Object)
|
|
||||||
if ok == false {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
value_type := reflect.TypeOf(p.Value)
|
|
||||||
for go_type, _ := range(valid_nodes) {
|
|
||||||
if value_type == go_type {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return false
|
|
||||||
},
|
|
||||||
Fields: graphql.Fields{},
|
|
||||||
})
|
|
||||||
|
|
||||||
gql_type_base_node.AddFieldConfig("ID", &graphql.Field{
|
|
||||||
Type: graphql.String,
|
|
||||||
Resolve: GQLNodeID,
|
|
||||||
})
|
|
||||||
|
|
||||||
gql_type_base_node.AddFieldConfig("Name", &graphql.Field{
|
|
||||||
Type: graphql.String,
|
|
||||||
Resolve: GQLNodeName,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
return gql_type_base_node
|
|
||||||
}
|
|
||||||
|
|
||||||
func GQLSignalFn(p graphql.ResolveParams, fn func(GraphSignal, graphql.ResolveParams)(interface{}, error))(interface{}, error) {
|
|
||||||
if signal, ok := p.Source.(GraphSignal); ok {
|
|
||||||
return fn(signal, p)
|
|
||||||
}
|
|
||||||
return nil, fmt.Errorf("Failed to cast source to event")
|
|
||||||
}
|
|
||||||
|
|
||||||
func GQLSignalType(p graphql.ResolveParams) (interface{}, error) {
|
|
||||||
return GQLSignalFn(p, func(signal GraphSignal, p graphql.ResolveParams)(interface{}, error){
|
|
||||||
return signal.Type(), nil
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
func GQLSignalSource(p graphql.ResolveParams) (interface{}, error) {
|
|
||||||
return GQLSignalFn(p, func(signal GraphSignal, p graphql.ResolveParams)(interface{}, error){
|
|
||||||
return signal.Source(), nil
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
func GQLSignalDirection(p graphql.ResolveParams) (interface{}, error) {
|
|
||||||
return GQLSignalFn(p, func(signal GraphSignal, p graphql.ResolveParams)(interface{}, error){
|
|
||||||
return signal.Direction(), nil
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
func GQLSignalString(p graphql.ResolveParams) (interface{}, error) {
|
|
||||||
return GQLSignalFn(p, func(signal GraphSignal, p graphql.ResolveParams)(interface{}, error){
|
|
||||||
return signal.String(), nil
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
var gql_type_signal *graphql.Object = nil
|
|
||||||
func GQLTypeSignal() *graphql.Object {
|
|
||||||
if gql_type_signal == nil {
|
|
||||||
gql_type_signal = graphql.NewObject(graphql.ObjectConfig{
|
|
||||||
Name: "SignalOut",
|
|
||||||
IsTypeOf: func(p graphql.IsTypeOfParams) bool {
|
|
||||||
_, ok := p.Value.(GraphSignal)
|
|
||||||
return ok
|
|
||||||
},
|
|
||||||
Fields: graphql.Fields{},
|
|
||||||
})
|
|
||||||
|
|
||||||
gql_type_signal.AddFieldConfig("Type", &graphql.Field{
|
|
||||||
Type: graphql.String,
|
|
||||||
Resolve: GQLSignalType,
|
|
||||||
})
|
|
||||||
gql_type_signal.AddFieldConfig("Source", &graphql.Field{
|
|
||||||
Type: graphql.String,
|
|
||||||
Resolve: GQLSignalSource,
|
|
||||||
})
|
|
||||||
gql_type_signal.AddFieldConfig("Direction", &graphql.Field{
|
|
||||||
Type: graphql.Boolean,
|
|
||||||
Resolve: GQLSignalDirection,
|
|
||||||
})
|
|
||||||
gql_type_signal.AddFieldConfig("String", &graphql.Field{
|
|
||||||
Type: graphql.String,
|
|
||||||
Resolve: GQLSignalString,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
return gql_type_signal
|
|
||||||
}
|
|
||||||
|
|
||||||
var gql_type_signal_input *graphql.InputObject = nil
|
|
||||||
func GQLTypeSignalInput() *graphql.InputObject {
|
|
||||||
if gql_type_signal_input == nil {
|
|
||||||
gql_type_signal_input = graphql.NewInputObject(graphql.InputObjectConfig{
|
|
||||||
Name: "SignalIn",
|
|
||||||
Fields: graphql.InputObjectConfigFieldMap{},
|
|
||||||
})
|
|
||||||
gql_type_signal_input.AddFieldConfig("Type", &graphql.InputObjectFieldConfig{
|
|
||||||
Type: graphql.String,
|
|
||||||
})
|
|
||||||
gql_type_signal_input.AddFieldConfig("Description", &graphql.InputObjectFieldConfig{
|
|
||||||
Type: graphql.String,
|
|
||||||
DefaultValue: "",
|
|
||||||
})
|
|
||||||
gql_type_signal_input.AddFieldConfig("Time", &graphql.InputObjectFieldConfig{
|
|
||||||
Type: graphql.DateTime,
|
|
||||||
DefaultValue: time.Now(),
|
|
||||||
})
|
|
||||||
}
|
|
||||||
return gql_type_signal_input
|
|
||||||
}
|
|
||||||
|
|
||||||
func GQLSubscribeSignal(p graphql.ResolveParams) (interface{}, error) {
|
|
||||||
return GQLSubscribeFn(p, func(signal GraphSignal, p graphql.ResolveParams)(interface{}, error) {
|
|
||||||
return signal, nil
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
func GQLSubscribeFn(p graphql.ResolveParams, fn func(GraphSignal, graphql.ResolveParams)(interface{}, error))(interface{}, error) {
|
|
||||||
server, ok := p.Context.Value("gql_server").(*GQLThread)
|
|
||||||
if ok == false {
|
|
||||||
return nil, fmt.Errorf("Failed to get gql_server from context and cast to GQLServer")
|
|
||||||
}
|
|
||||||
|
|
||||||
ctx, ok := p.Context.Value("graph_context").(*GraphContext)
|
|
||||||
if ok == false {
|
|
||||||
return nil, fmt.Errorf("Failed to get graph_context from context and cast to GraphContext")
|
|
||||||
}
|
|
||||||
|
|
||||||
c := make(chan interface{})
|
|
||||||
go func(c chan interface{}, server *GQLThread) {
|
|
||||||
sig_c := server.UpdateChannel(0)
|
|
||||||
for {
|
|
||||||
val, ok := <- sig_c
|
|
||||||
if ok == false {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
ret, err := fn(val, p)
|
|
||||||
if err != nil {
|
|
||||||
ctx.Log.Logf("gqlws", "type convertor error %s", err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
c <- ret
|
|
||||||
}
|
|
||||||
}(c, server)
|
|
||||||
return c, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
var gql_subscription_update * graphql.Field = nil
|
|
||||||
func GQLSubscriptionUpdate() * graphql.Field {
|
|
||||||
if gql_subscription_update == nil {
|
|
||||||
gql_subscription_update = &graphql.Field{
|
|
||||||
Type: GQLTypeSignal(),
|
|
||||||
Resolve: func(p graphql.ResolveParams) (interface{}, error) {
|
|
||||||
return p.Source, nil
|
|
||||||
},
|
|
||||||
Subscribe: GQLSubscribeSignal,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return gql_subscription_update
|
|
||||||
}
|
|
||||||
|
|
||||||
var gql_mutation_send_update *graphql.Field = nil
|
|
||||||
func GQLMutationSendUpdate() *graphql.Field {
|
|
||||||
if gql_mutation_send_update == nil {
|
|
||||||
gql_mutation_send_update = &graphql.Field{
|
|
||||||
Type: GQLTypeSignal(),
|
|
||||||
Args: graphql.FieldConfigArgument{
|
|
||||||
"id": &graphql.ArgumentConfig{
|
|
||||||
Type: graphql.String,
|
|
||||||
},
|
|
||||||
"signal": &graphql.ArgumentConfig{
|
|
||||||
Type: GQLTypeSignalInput(),
|
|
||||||
},
|
|
||||||
},
|
|
||||||
Resolve: func(p graphql.ResolveParams) (interface{}, error) {
|
|
||||||
server, ok := p.Context.Value("gql_server").(*GQLThread)
|
|
||||||
if ok == false {
|
|
||||||
return nil, fmt.Errorf("Failed to cast context gql_server to GQLServer: %+v", p.Context.Value("gql_server"))
|
|
||||||
}
|
|
||||||
|
|
||||||
ctx, ok := p.Context.Value("graph_context").(*GraphContext)
|
|
||||||
if ok == false {
|
|
||||||
return nil, fmt.Errorf("Failed to cast context graph_context to GraphContext: %+v", p.Context.Value("graph_context"))
|
|
||||||
}
|
|
||||||
|
|
||||||
signal_map, ok := p.Args["signal"].(map[string]interface{})
|
|
||||||
if ok == false {
|
|
||||||
return nil, fmt.Errorf("Failed to cast arg signal to GraphSignal: %+v", p.Args["signal"])
|
|
||||||
}
|
|
||||||
var signal GraphSignal = nil
|
|
||||||
if signal_map["Direction"] == Up {
|
|
||||||
signal = NewSignal(server, signal_map["Type"].(string))
|
|
||||||
} else if signal_map["Direction"] == Down {
|
|
||||||
signal = NewDownSignal(server, signal_map["Type"].(string))
|
|
||||||
} else if signal_map["Direction"] == Direct {
|
|
||||||
signal = NewDirectSignal(server, signal_map["Type"].(string))
|
|
||||||
} else {
|
|
||||||
return nil, fmt.Errorf("Bad direction: %d", signal_map["Direction"])
|
|
||||||
}
|
|
||||||
|
|
||||||
id , ok := p.Args["id"].(NodeID)
|
|
||||||
if ok == false {
|
|
||||||
return nil, fmt.Errorf("Failed to cast arg id to string")
|
|
||||||
}
|
|
||||||
|
|
||||||
node_if, err := UseStates(ctx, []GraphNode{server}, func(states []NodeState) (interface{}, error){
|
|
||||||
server_state := states[0].(*GQLThreadState)
|
|
||||||
node := FindChild(ctx, server, server_state, id)
|
|
||||||
if node == nil {
|
|
||||||
return nil, fmt.Errorf("Failed to find ID: %s as child of server thread", id)
|
|
||||||
}
|
|
||||||
return node, nil
|
|
||||||
})
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
node, ok := node_if.(GraphNode)
|
|
||||||
if ok == false {
|
|
||||||
return nil, fmt.Errorf("Failed to cast found node to GraphNode")
|
|
||||||
}
|
|
||||||
|
|
||||||
SendUpdate(ctx, node, signal)
|
|
||||||
return signal, nil
|
|
||||||
},
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return gql_mutation_send_update
|
|
||||||
}
|
|
||||||
|
|
||||||
var gql_query_self *graphql.Field = nil
|
|
||||||
func GQLQuerySelf() *graphql.Field {
|
|
||||||
if gql_query_self == nil {
|
|
||||||
gql_query_self = &graphql.Field{
|
|
||||||
Type: GQLTypeGQLThread(),
|
|
||||||
Resolve: func(p graphql.ResolveParams) (interface{}, error) {
|
|
||||||
server, ok := p.Context.Value("gql_server").(*GQLThread)
|
|
||||||
if ok == false {
|
|
||||||
return nil, fmt.Errorf("failed to cast gql_server to GQLThread")
|
|
||||||
}
|
|
||||||
|
|
||||||
return server, nil
|
|
||||||
},
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return gql_query_self
|
|
||||||
}
|
|
@ -0,0 +1,147 @@
|
|||||||
|
package graphvent
|
||||||
|
import (
|
||||||
|
"reflect"
|
||||||
|
"fmt"
|
||||||
|
"time"
|
||||||
|
"github.com/graphql-go/graphql"
|
||||||
|
"github.com/graphql-go/graphql/language/ast"
|
||||||
|
)
|
||||||
|
|
||||||
|
func ResolveNodeID(p graphql.ResolveParams) (interface{}, error) {
|
||||||
|
node, ok := p.Source.(NodeResult)
|
||||||
|
if ok == false {
|
||||||
|
return nil, fmt.Errorf("Can't get NodeID from %+v", reflect.TypeOf(p.Source))
|
||||||
|
}
|
||||||
|
|
||||||
|
return node.NodeID, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func ResolveNodeType(p graphql.ResolveParams) (interface{}, error) {
|
||||||
|
node, ok := p.Source.(NodeResult)
|
||||||
|
if ok == false {
|
||||||
|
return nil, fmt.Errorf("Can't get TypeHash from %+v", reflect.TypeOf(p.Source))
|
||||||
|
}
|
||||||
|
|
||||||
|
return uint64(node.NodeType), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
type FieldIndex struct {
|
||||||
|
Extension ExtType
|
||||||
|
Tag string
|
||||||
|
}
|
||||||
|
|
||||||
|
func GetFields(selection_set *ast.SelectionSet) []string {
|
||||||
|
names := []string{}
|
||||||
|
if selection_set == nil {
|
||||||
|
return names
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, sel := range(selection_set.Selections) {
|
||||||
|
switch field := sel.(type) {
|
||||||
|
case *ast.Field:
|
||||||
|
if field.Name.Value == "ID" || field.Name.Value == "Type" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
names = append(names, field.Name.Value)
|
||||||
|
case *ast.InlineFragment:
|
||||||
|
names = append(names, GetFields(field.SelectionSet)...)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return names
|
||||||
|
}
|
||||||
|
|
||||||
|
// Returns the fields that need to be resolved
|
||||||
|
func GetResolveFields(p graphql.ResolveParams) []string {
|
||||||
|
fields := []string{}
|
||||||
|
for _, field := range(p.Info.FieldASTs) {
|
||||||
|
fields = append(fields, GetFields(field.SelectionSet)...)
|
||||||
|
}
|
||||||
|
|
||||||
|
return fields
|
||||||
|
}
|
||||||
|
|
||||||
|
func ResolveNode(id NodeID, p graphql.ResolveParams) (NodeResult, error) {
|
||||||
|
ctx, err := PrepResolve(p)
|
||||||
|
if err != nil {
|
||||||
|
return NodeResult{}, err
|
||||||
|
}
|
||||||
|
|
||||||
|
switch source := p.Source.(type) {
|
||||||
|
case *StatusSignal:
|
||||||
|
cached_node, cached := ctx.NodeCache[source.Source]
|
||||||
|
if cached {
|
||||||
|
for _, field_name := range(source.Fields) {
|
||||||
|
_, cached := cached_node.Data[field_name]
|
||||||
|
if cached {
|
||||||
|
delete(cached_node.Data, field_name)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
ctx.NodeCache[source.Source] = cached_node
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
cache, node_cached := ctx.NodeCache[id]
|
||||||
|
fields := GetResolveFields(p)
|
||||||
|
var not_cached []string
|
||||||
|
if node_cached {
|
||||||
|
not_cached = []string{}
|
||||||
|
for _, field := range(fields) {
|
||||||
|
if node_cached {
|
||||||
|
_, field_cached := cache.Data[field]
|
||||||
|
if field_cached {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
not_cached = append(not_cached, field)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
not_cached = fields
|
||||||
|
}
|
||||||
|
|
||||||
|
if (len(not_cached) == 0) && (node_cached == true) {
|
||||||
|
ctx.Context.Log.Logf("gql", "No new fields to resolve for %s", id)
|
||||||
|
return cache, nil
|
||||||
|
} else {
|
||||||
|
ctx.Context.Log.Logf("gql", "Resolving fields %+v on node %s", not_cached, id)
|
||||||
|
|
||||||
|
signal := NewReadSignal(not_cached)
|
||||||
|
response_chan := ctx.Ext.GetResponseChannel(signal.ID())
|
||||||
|
// TODO: TIMEOUT DURATION
|
||||||
|
err = ctx.Context.Send(ctx.Server, []Message{{
|
||||||
|
Node: id,
|
||||||
|
Signal: signal,
|
||||||
|
}})
|
||||||
|
if err != nil {
|
||||||
|
ctx.Ext.FreeResponseChannel(signal.ID())
|
||||||
|
return NodeResult{}, err
|
||||||
|
}
|
||||||
|
|
||||||
|
response, _, err := WaitForResponse(response_chan, 100*time.Millisecond, signal.ID())
|
||||||
|
ctx.Ext.FreeResponseChannel(signal.ID())
|
||||||
|
if err != nil {
|
||||||
|
return NodeResult{}, err
|
||||||
|
}
|
||||||
|
|
||||||
|
switch response := response.(type) {
|
||||||
|
case *ReadResultSignal:
|
||||||
|
if node_cached == false {
|
||||||
|
cache = NodeResult{
|
||||||
|
NodeID: id,
|
||||||
|
NodeType: response.NodeType,
|
||||||
|
Data: response.Fields,
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
for field_name, field_value := range(response.Fields) {
|
||||||
|
cache.Data[field_name] = field_value
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
ctx.NodeCache[id] = cache
|
||||||
|
return ctx.NodeCache[id], nil
|
||||||
|
default:
|
||||||
|
return NodeResult{}, fmt.Errorf("Bad read response: %+v", response)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
@ -1,20 +1,223 @@
|
|||||||
package graphvent
|
package graphvent
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"bytes"
|
||||||
|
"crypto/tls"
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"net"
|
||||||
|
"net/http"
|
||||||
|
"reflect"
|
||||||
"testing"
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/google/uuid"
|
||||||
|
"golang.org/x/net/websocket"
|
||||||
)
|
)
|
||||||
|
|
||||||
func TestGQLThread(t * testing.T) {
|
func TestGQLSubscribe(t *testing.T) {
|
||||||
ctx := testContext(t)
|
ctx := logTestContext(t, []string{"test", "gql"})
|
||||||
gql_thread, err := NewGQLThread(ctx, ":8080", []Lockable{}, ObjTypeMap{}, FieldMap{}, FieldMap{}, FieldMap{})
|
|
||||||
|
n1, err := ctx.NewNode(nil, "LockableNode", NewLockableExt(nil))
|
||||||
|
fatalErr(t, err)
|
||||||
|
|
||||||
|
listener_ext := NewListenerExt(10)
|
||||||
|
|
||||||
|
gql_ext, err := NewGQLExt(ctx, ":0", nil, nil)
|
||||||
|
fatalErr(t, err)
|
||||||
|
|
||||||
|
gql, err := ctx.NewNode(nil, "LockableNode", NewLockableExt([]NodeID{n1.ID}), gql_ext, listener_ext)
|
||||||
|
fatalErr(t, err)
|
||||||
|
|
||||||
|
query := "subscription { Self { ID, Type ... on Lockable { LockableState } } }"
|
||||||
|
|
||||||
|
ctx.Log.Logf("test", "GQL: %s", gql.ID)
|
||||||
|
ctx.Log.Logf("test", "Node: %s", n1.ID)
|
||||||
|
ctx.Log.Logf("test", "Query: %s", query)
|
||||||
|
|
||||||
|
sub_1 := GQLPayload{
|
||||||
|
Query: query,
|
||||||
|
}
|
||||||
|
|
||||||
|
port := gql_ext.tcp_listener.Addr().(*net.TCPAddr).Port
|
||||||
|
url := fmt.Sprintf("http://localhost:%d/gql", port)
|
||||||
|
ws_url := fmt.Sprintf("ws://127.0.0.1:%d/gqlws", port)
|
||||||
|
|
||||||
|
SubGQL := func(payload GQLPayload) {
|
||||||
|
config, err := websocket.NewConfig(ws_url, url)
|
||||||
|
fatalErr(t, err)
|
||||||
|
config.Protocol = append(config.Protocol, "graphql-ws")
|
||||||
|
config.TlsConfig = &tls.Config{InsecureSkipVerify: true}
|
||||||
|
|
||||||
|
ws, err := websocket.DialConfig(config)
|
||||||
|
|
||||||
|
fatalErr(t, err)
|
||||||
|
|
||||||
|
type payload_struct struct {
|
||||||
|
Token string `json:"token"`
|
||||||
|
}
|
||||||
|
|
||||||
|
init := struct{
|
||||||
|
ID uuid.UUID `json:"id"`
|
||||||
|
Type string `json:"type"`
|
||||||
|
}{
|
||||||
|
uuid.New(),
|
||||||
|
"connection_init",
|
||||||
|
}
|
||||||
|
|
||||||
|
ser, err := json.Marshal(&init)
|
||||||
|
fatalErr(t, err)
|
||||||
|
|
||||||
|
_, err = ws.Write(ser)
|
||||||
|
fatalErr(t, err)
|
||||||
|
|
||||||
|
resp := make([]byte, 1024)
|
||||||
|
n, err := ws.Read(resp)
|
||||||
|
|
||||||
|
var init_resp GQLWSMsg
|
||||||
|
err = json.Unmarshal(resp[:n], &init_resp)
|
||||||
|
fatalErr(t, err)
|
||||||
|
|
||||||
|
if init_resp.Type != "connection_ack" {
|
||||||
|
t.Fatal("Didn't receive connection_ack")
|
||||||
|
}
|
||||||
|
|
||||||
|
sub := GQLWSMsg{
|
||||||
|
ID: uuid.New().String(),
|
||||||
|
Type: "subscribe",
|
||||||
|
Payload: sub_1,
|
||||||
|
}
|
||||||
|
|
||||||
|
ser, err = json.Marshal(&sub)
|
||||||
|
fatalErr(t, err)
|
||||||
|
_, err = ws.Write(ser)
|
||||||
|
fatalErr(t, err)
|
||||||
|
|
||||||
|
n, err = ws.Read(resp)
|
||||||
|
fatalErr(t, err)
|
||||||
|
ctx.Log.Logf("test", "SUB1: %s", resp[:n])
|
||||||
|
|
||||||
|
lock_id, err := LockLockable(ctx, gql)
|
||||||
|
fatalErr(t, err)
|
||||||
|
|
||||||
|
response, _, err := WaitForResponse(listener_ext.Chan, 100*time.Millisecond, lock_id)
|
||||||
|
fatalErr(t, err)
|
||||||
|
|
||||||
|
switch response.(type) {
|
||||||
|
case *SuccessSignal:
|
||||||
|
ctx.Log.Logf("test", "Locked %s", gql.ID)
|
||||||
|
default:
|
||||||
|
t.Errorf("Unexpected lock response: %s", response)
|
||||||
|
}
|
||||||
|
|
||||||
|
n, err = ws.Read(resp)
|
||||||
|
fatalErr(t, err)
|
||||||
|
ctx.Log.Logf("test", "SUB2: %s", resp[:n])
|
||||||
|
|
||||||
|
n, err = ws.Read(resp)
|
||||||
|
fatalErr(t, err)
|
||||||
|
ctx.Log.Logf("test", "SUB3: %s", resp[:n])
|
||||||
|
|
||||||
|
// TODO: check that there are no more messages sent to ws within a timeout
|
||||||
|
}
|
||||||
|
|
||||||
|
SubGQL(sub_1)
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestGQLQuery(t *testing.T) {
|
||||||
|
ctx := logTestContext(t, []string{"test", "lockable"})
|
||||||
|
|
||||||
|
n1_listener := NewListenerExt(10)
|
||||||
|
n1, err := ctx.NewNode(nil, "LockableNode", NewLockableExt(nil), n1_listener)
|
||||||
|
fatalErr(t, err)
|
||||||
|
|
||||||
|
gql_listener := NewListenerExt(10)
|
||||||
|
gql_ext, err := NewGQLExt(ctx, ":0", nil, nil)
|
||||||
|
fatalErr(t, err)
|
||||||
|
|
||||||
|
gql, err := ctx.NewNode(nil, "LockableNode", NewLockableExt([]NodeID{n1.ID}), gql_ext, gql_listener)
|
||||||
|
fatalErr(t, err)
|
||||||
|
|
||||||
|
ctx.Log.Logf("test", "GQL: %s", gql.ID)
|
||||||
|
ctx.Log.Logf("test", "NODE: %s", n1.ID)
|
||||||
|
|
||||||
|
skipVerifyTransport := &http.Transport{
|
||||||
|
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
|
||||||
|
}
|
||||||
|
client := &http.Client{Transport: skipVerifyTransport}
|
||||||
|
port := gql_ext.tcp_listener.Addr().(*net.TCPAddr).Port
|
||||||
|
url := fmt.Sprintf("http://localhost:%d/gql", port)
|
||||||
|
|
||||||
|
req_1 := GQLPayload{
|
||||||
|
Query: "query Node($id:graphvent_NodeID) { Node(id:$id) { ID, Type, ... on Lockable { LockableState } } }",
|
||||||
|
Variables: map[string]interface{}{
|
||||||
|
"id": n1.ID.String(),
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
req_2 := GQLPayload{
|
||||||
|
Query: "query Self { Self { ID, Type, ... on Lockable { LockableState, Requirements { Key { ID ... on Lockable { LockableState } } } } } }",
|
||||||
|
}
|
||||||
|
|
||||||
|
SendGQL := func(payload GQLPayload) []byte {
|
||||||
|
ser, err := json.MarshalIndent(&payload, "", " ")
|
||||||
|
fatalErr(t, err)
|
||||||
|
|
||||||
|
req_data := bytes.NewBuffer(ser)
|
||||||
|
req, err := http.NewRequest("GET", url, req_data)
|
||||||
|
fatalErr(t, err)
|
||||||
|
|
||||||
|
resp, err := client.Do(req)
|
||||||
|
fatalErr(t, err)
|
||||||
|
|
||||||
|
body, err := io.ReadAll(resp.Body)
|
||||||
|
fatalErr(t, err)
|
||||||
|
|
||||||
|
resp.Body.Close()
|
||||||
|
return body
|
||||||
|
}
|
||||||
|
|
||||||
|
resp_1 := SendGQL(req_1)
|
||||||
|
ctx.Log.Logf("test", "RESP_1: %s", resp_1)
|
||||||
|
resp_2 := SendGQL(req_2)
|
||||||
|
ctx.Log.Logf("test", "RESP_2: %s", resp_2)
|
||||||
|
|
||||||
|
lock_id, err := LockLockable(ctx, n1)
|
||||||
|
fatalErr(t, err)
|
||||||
|
|
||||||
|
response, _, err := WaitForResponse(n1_listener.Chan, 100*time.Millisecond, lock_id)
|
||||||
|
fatalErr(t, err)
|
||||||
|
switch response := response.(type) {
|
||||||
|
case *SuccessSignal:
|
||||||
|
default:
|
||||||
|
t.Fatalf("Wrong response: %s", reflect.TypeOf(response))
|
||||||
|
}
|
||||||
|
|
||||||
|
resp_3 := SendGQL(req_1)
|
||||||
|
ctx.Log.Logf("test", "RESP_3: %s", resp_3)
|
||||||
|
|
||||||
|
resp_4 := SendGQL(req_2)
|
||||||
|
ctx.Log.Logf("test", "RESP_4: %s", resp_4)
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestGQLDB(t *testing.T) {
|
||||||
|
ctx := logTestContext(t, []string{"test", "db", "node", "serialize"})
|
||||||
|
|
||||||
|
gql_ext, err := NewGQLExt(ctx, ":0", nil, nil)
|
||||||
|
fatalErr(t, err)
|
||||||
|
listener_ext := NewListenerExt(10)
|
||||||
|
|
||||||
|
gql, err := ctx.NewNode(nil, "Node", gql_ext, listener_ext)
|
||||||
fatalErr(t, err)
|
fatalErr(t, err)
|
||||||
|
ctx.Log.Logf("test", "GQL_ID: %s", gql.ID)
|
||||||
|
|
||||||
test_thread, err := NewSimpleBaseThread(ctx, "Test thread 1", []Lockable{}, ThreadActions{}, ThreadHandlers{})
|
err = ctx.Stop()
|
||||||
fatalErr(t, err)
|
fatalErr(t, err)
|
||||||
|
|
||||||
err = LinkThreads(ctx, gql_thread, test_thread, nil)
|
gql_loaded, err := ctx.GetNode(gql.ID)
|
||||||
fatalErr(t, err)
|
fatalErr(t, err)
|
||||||
|
|
||||||
err = RunThread(ctx, gql_thread)
|
listener_ext, err = GetExt[ListenerExt](gql_loaded)
|
||||||
fatalErr(t, err)
|
fatalErr(t, err)
|
||||||
}
|
}
|
||||||
|
@ -1,432 +0,0 @@
|
|||||||
package graphvent
|
|
||||||
|
|
||||||
import (
|
|
||||||
"sync"
|
|
||||||
"reflect"
|
|
||||||
"github.com/google/uuid"
|
|
||||||
"os"
|
|
||||||
"github.com/rs/zerolog"
|
|
||||||
"fmt"
|
|
||||||
badger "github.com/dgraph-io/badger/v3"
|
|
||||||
"encoding/json"
|
|
||||||
)
|
|
||||||
|
|
||||||
type GraphContext struct {
|
|
||||||
DB * badger.DB
|
|
||||||
Log Logger
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewGraphContext(db * badger.DB, log Logger) * GraphContext {
|
|
||||||
return &GraphContext{DB: db, Log: log}
|
|
||||||
}
|
|
||||||
|
|
||||||
// A Logger is passed around to record events happening to components enabled by SetComponents
|
|
||||||
type Logger interface {
|
|
||||||
SetComponents(components []string) error
|
|
||||||
// Log a formatted string
|
|
||||||
Logf(component string, format string, items ... interface{})
|
|
||||||
// Log a map of attributes and a format string
|
|
||||||
Logm(component string, fields map[string]interface{}, format string, items ... interface{})
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewConsoleLogger(components []string) *ConsoleLogger {
|
|
||||||
logger := &ConsoleLogger{
|
|
||||||
loggers: map[string]zerolog.Logger{},
|
|
||||||
components: []string{},
|
|
||||||
}
|
|
||||||
|
|
||||||
logger.SetComponents(components)
|
|
||||||
|
|
||||||
return logger
|
|
||||||
}
|
|
||||||
|
|
||||||
// A ConsoleLogger logs to stdout
|
|
||||||
type ConsoleLogger struct {
|
|
||||||
loggers map[string]zerolog.Logger
|
|
||||||
components_lock sync.Mutex
|
|
||||||
components []string
|
|
||||||
}
|
|
||||||
|
|
||||||
func (logger * ConsoleLogger) SetComponents(components []string) error {
|
|
||||||
logger.components_lock.Lock()
|
|
||||||
defer logger.components_lock.Unlock()
|
|
||||||
|
|
||||||
component_enabled := func (component string) bool {
|
|
||||||
for _, c := range(components) {
|
|
||||||
if c == component {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
for c, _ := range(logger.loggers) {
|
|
||||||
if component_enabled(c) == false {
|
|
||||||
delete(logger.loggers, c)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, c := range(components) {
|
|
||||||
_, exists := logger.loggers[c]
|
|
||||||
if component_enabled(c) == true && exists == false {
|
|
||||||
logger.loggers[c] = zerolog.New(os.Stdout).With().Timestamp().Str("component", c).Logger()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (logger * ConsoleLogger) Logm(component string, fields map[string]interface{}, format string, items ... interface{}) {
|
|
||||||
l, exists := logger.loggers[component]
|
|
||||||
if exists == true {
|
|
||||||
log := l.Log()
|
|
||||||
for key, value := range(fields) {
|
|
||||||
log = log.Str(key, fmt.Sprintf("%+v", value))
|
|
||||||
}
|
|
||||||
log.Msg(fmt.Sprintf(format, items...))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (logger * ConsoleLogger) Logf(component string, format string, items ... interface{}) {
|
|
||||||
l, exists := logger.loggers[component]
|
|
||||||
if exists == true {
|
|
||||||
l.Log().Msg(fmt.Sprintf(format, items...))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
type NodeID string
|
|
||||||
// Generate a random id
|
|
||||||
func RandID() NodeID {
|
|
||||||
uuid_str := uuid.New().String()
|
|
||||||
return NodeID(uuid_str)
|
|
||||||
}
|
|
||||||
|
|
||||||
type SignalDirection int
|
|
||||||
const (
|
|
||||||
Up SignalDirection = iota
|
|
||||||
Down
|
|
||||||
Direct
|
|
||||||
)
|
|
||||||
|
|
||||||
// GraphSignals are passed around the event tree/resource DAG and cast by Type()
|
|
||||||
type GraphSignal interface {
|
|
||||||
// How to propogate the signal
|
|
||||||
Direction() SignalDirection
|
|
||||||
Source() NodeID
|
|
||||||
Type() string
|
|
||||||
String() string
|
|
||||||
}
|
|
||||||
|
|
||||||
// BaseSignal is the most basic type of signal, it has no additional data
|
|
||||||
type BaseSignal struct {
|
|
||||||
direction SignalDirection
|
|
||||||
source NodeID
|
|
||||||
_type string
|
|
||||||
}
|
|
||||||
|
|
||||||
func (signal BaseSignal) Direction() SignalDirection {
|
|
||||||
return signal.direction
|
|
||||||
}
|
|
||||||
|
|
||||||
func (signal BaseSignal) Source() NodeID {
|
|
||||||
return signal.source
|
|
||||||
}
|
|
||||||
|
|
||||||
func (signal BaseSignal) Type() string {
|
|
||||||
return signal._type
|
|
||||||
}
|
|
||||||
|
|
||||||
func (signal BaseSignal) String() string {
|
|
||||||
return fmt.Sprintf("{direction: %d, source: %s, type: %s}", signal.direction, signal.source, signal._type)
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewBaseSignal(source GraphNode, _type string, direction SignalDirection) BaseSignal {
|
|
||||||
var source_id NodeID = ""
|
|
||||||
if source != nil {
|
|
||||||
source_id = source.ID()
|
|
||||||
}
|
|
||||||
|
|
||||||
signal := BaseSignal{
|
|
||||||
direction: direction,
|
|
||||||
source: source_id,
|
|
||||||
_type: _type,
|
|
||||||
}
|
|
||||||
return signal
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewDownSignal(source GraphNode, _type string) BaseSignal {
|
|
||||||
return NewBaseSignal(source, _type, Down)
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewSignal(source GraphNode, _type string) BaseSignal {
|
|
||||||
return NewBaseSignal(source, _type, Up)
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewDirectSignal(source GraphNode, _type string) BaseSignal {
|
|
||||||
return NewBaseSignal(source, _type, Direct)
|
|
||||||
}
|
|
||||||
|
|
||||||
func AbortSignal(source GraphNode) BaseSignal {
|
|
||||||
return NewBaseSignal(source, "abort", Down)
|
|
||||||
}
|
|
||||||
|
|
||||||
func CancelSignal(source GraphNode) BaseSignal {
|
|
||||||
return NewBaseSignal(source, "cancel", Down)
|
|
||||||
}
|
|
||||||
|
|
||||||
type NodeState interface {
|
|
||||||
Name() string
|
|
||||||
}
|
|
||||||
|
|
||||||
// GraphNode is the interface common to both DAG nodes and Event tree nodes
|
|
||||||
// They have a NodeState interface which is saved to the database every update
|
|
||||||
type GraphNode interface {
|
|
||||||
ID() NodeID
|
|
||||||
|
|
||||||
State() NodeState
|
|
||||||
StateLock() *sync.RWMutex
|
|
||||||
|
|
||||||
SetState(new_state NodeState)
|
|
||||||
|
|
||||||
// Signal propagation function for listener channels
|
|
||||||
UpdateListeners(ctx * GraphContext, update GraphSignal)
|
|
||||||
// Signal propagation function for connected nodes(defined in state)
|
|
||||||
PropagateUpdate(ctx * GraphContext, update GraphSignal)
|
|
||||||
|
|
||||||
// Get an update channel for the node to be notified of signals
|
|
||||||
UpdateChannel(buffer int) chan GraphSignal
|
|
||||||
|
|
||||||
// Register and unregister a channel to propogate updates to
|
|
||||||
RegisterChannel(listener chan GraphSignal)
|
|
||||||
UnregisterChannel(listener chan GraphSignal)
|
|
||||||
// Get a handle to the nodes internal signal channel
|
|
||||||
SignalChannel() chan GraphSignal
|
|
||||||
}
|
|
||||||
|
|
||||||
// Create a new base node with the given ID
|
|
||||||
func NewNode(ctx * GraphContext, id NodeID, state NodeState) BaseNode {
|
|
||||||
node := BaseNode{
|
|
||||||
id: id,
|
|
||||||
signal: make(chan GraphSignal, 512),
|
|
||||||
listeners: map[chan GraphSignal]chan GraphSignal{},
|
|
||||||
state: state,
|
|
||||||
}
|
|
||||||
|
|
||||||
err := WriteDBState(ctx, id, state)
|
|
||||||
if err != nil {
|
|
||||||
panic(fmt.Sprintf("DB_NEW_WRITE_ERROR: %s", err))
|
|
||||||
}
|
|
||||||
|
|
||||||
ctx.Log.Logf("graph", "NEW_NODE: %s - %+v", id, state)
|
|
||||||
return node
|
|
||||||
}
|
|
||||||
|
|
||||||
// BaseNode is the minimum set of fields needed to implement a GraphNode,
|
|
||||||
// and provides a template for more complicated Nodes
|
|
||||||
type BaseNode struct {
|
|
||||||
id NodeID
|
|
||||||
|
|
||||||
state NodeState
|
|
||||||
state_lock sync.RWMutex
|
|
||||||
|
|
||||||
signal chan GraphSignal
|
|
||||||
|
|
||||||
listeners_lock sync.Mutex
|
|
||||||
listeners map[chan GraphSignal]chan GraphSignal
|
|
||||||
}
|
|
||||||
|
|
||||||
func (node * BaseNode) ID() NodeID {
|
|
||||||
return node.id
|
|
||||||
}
|
|
||||||
|
|
||||||
func (node * BaseNode) State() NodeState {
|
|
||||||
return node.state
|
|
||||||
}
|
|
||||||
|
|
||||||
func (node * BaseNode) StateLock() * sync.RWMutex {
|
|
||||||
return &node.state_lock
|
|
||||||
}
|
|
||||||
|
|
||||||
func WriteDBState(ctx * GraphContext, id NodeID, state NodeState) error {
|
|
||||||
ctx.Log.Logf("db", "DB_WRITE: %s - %+v", id, state)
|
|
||||||
|
|
||||||
var serialized_state []byte = nil
|
|
||||||
if state != nil {
|
|
||||||
ser, err := json.Marshal(state)
|
|
||||||
if err != nil {
|
|
||||||
return fmt.Errorf("DB_MARSHAL_ERROR: %e", err)
|
|
||||||
}
|
|
||||||
serialized_state = ser
|
|
||||||
} else {
|
|
||||||
serialized_state = []byte{}
|
|
||||||
}
|
|
||||||
|
|
||||||
err := ctx.DB.Update(func(txn *badger.Txn) error {
|
|
||||||
err := txn.Set([]byte(id), serialized_state)
|
|
||||||
return err
|
|
||||||
})
|
|
||||||
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
func (node * BaseNode) SetState(new_state NodeState) {
|
|
||||||
node.state = new_state
|
|
||||||
}
|
|
||||||
|
|
||||||
func checkForDuplicate(nodes []GraphNode) error {
|
|
||||||
found := map[NodeID]bool{}
|
|
||||||
for _, node := range(nodes) {
|
|
||||||
if node == nil {
|
|
||||||
return fmt.Errorf("Cannot get state of nil node")
|
|
||||||
}
|
|
||||||
|
|
||||||
_, exists := found[node.ID()]
|
|
||||||
if exists == true {
|
|
||||||
return fmt.Errorf("Attempted to get state of %s twice", node.ID())
|
|
||||||
}
|
|
||||||
found[node.ID()] = true
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func UseStates(ctx * GraphContext, nodes []GraphNode, states_fn func(states []NodeState)(interface{}, error)) (interface{}, error) {
|
|
||||||
err := checkForDuplicate(nodes)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, node := range(nodes) {
|
|
||||||
node.StateLock().RLock()
|
|
||||||
}
|
|
||||||
|
|
||||||
states := make([]NodeState, len(nodes))
|
|
||||||
for i, node := range(nodes) {
|
|
||||||
states[i] = node.State()
|
|
||||||
}
|
|
||||||
|
|
||||||
val, err := states_fn(states)
|
|
||||||
|
|
||||||
for _, node := range(nodes) {
|
|
||||||
node.StateLock().RUnlock()
|
|
||||||
}
|
|
||||||
|
|
||||||
return val, err
|
|
||||||
}
|
|
||||||
|
|
||||||
func UpdateStates(ctx * GraphContext, nodes []GraphNode, states_fn func(states []NodeState)([]NodeState, interface{}, error)) (interface{}, error) {
|
|
||||||
err := checkForDuplicate(nodes)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, node := range(nodes) {
|
|
||||||
node.StateLock().Lock()
|
|
||||||
}
|
|
||||||
|
|
||||||
states := make([]NodeState, len(nodes))
|
|
||||||
for i, node := range(nodes) {
|
|
||||||
states[i] = node.State()
|
|
||||||
}
|
|
||||||
|
|
||||||
new_states, val, err := states_fn(states)
|
|
||||||
|
|
||||||
if new_states != nil {
|
|
||||||
if len(new_states) != len(nodes) {
|
|
||||||
panic(fmt.Sprintf("NODE_NEW_STATE_LEN_MISMATCH: %d/%d", len(new_states), len(nodes)))
|
|
||||||
}
|
|
||||||
|
|
||||||
for i, new_state := range(new_states) {
|
|
||||||
if new_state != nil {
|
|
||||||
old_state_type := reflect.TypeOf(states[i])
|
|
||||||
new_state_type := reflect.TypeOf(new_state)
|
|
||||||
|
|
||||||
if old_state_type != new_state_type {
|
|
||||||
panic(fmt.Sprintf("NODE_STATE_MISMATCH: old - %+v, new - %+v", old_state_type, new_state_type))
|
|
||||||
}
|
|
||||||
|
|
||||||
err := WriteDBState(ctx, nodes[i].ID(), new_state)
|
|
||||||
if err != nil {
|
|
||||||
panic(fmt.Sprintf("DB_WRITE_ERROR: %s", err))
|
|
||||||
}
|
|
||||||
|
|
||||||
nodes[i].SetState(new_state)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, node := range(nodes) {
|
|
||||||
node.StateLock().Unlock()
|
|
||||||
}
|
|
||||||
|
|
||||||
return val, err
|
|
||||||
}
|
|
||||||
|
|
||||||
func (node * BaseNode) UpdateListeners(ctx * GraphContext, update GraphSignal) {
|
|
||||||
node.listeners_lock.Lock()
|
|
||||||
defer node.listeners_lock.Unlock()
|
|
||||||
closed := []chan GraphSignal{}
|
|
||||||
|
|
||||||
for _, listener := range node.listeners {
|
|
||||||
ctx.Log.Logf("listeners", "UPDATE_LISTENER %s: %p", node.ID(), listener)
|
|
||||||
select {
|
|
||||||
case listener <- update:
|
|
||||||
default:
|
|
||||||
ctx.Log.Logf("listeners", "CLOSED_LISTENER %s: %p", node.ID(), listener)
|
|
||||||
go func(node GraphNode, listener chan GraphSignal) {
|
|
||||||
listener <- NewSignal(node, "listener_closed")
|
|
||||||
close(listener)
|
|
||||||
}(node, listener)
|
|
||||||
closed = append(closed, listener)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, listener := range(closed) {
|
|
||||||
delete(node.listeners, listener)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (node * BaseNode) PropagateUpdate(ctx * GraphContext, update GraphSignal) {
|
|
||||||
}
|
|
||||||
|
|
||||||
func (node * BaseNode) RegisterChannel(listener chan GraphSignal) {
|
|
||||||
node.listeners_lock.Lock()
|
|
||||||
_, exists := node.listeners[listener]
|
|
||||||
if exists == false {
|
|
||||||
node.listeners[listener] = listener
|
|
||||||
}
|
|
||||||
node.listeners_lock.Unlock()
|
|
||||||
}
|
|
||||||
|
|
||||||
func (node * BaseNode) UnregisterChannel(listener chan GraphSignal) {
|
|
||||||
node.listeners_lock.Lock()
|
|
||||||
_, exists := node.listeners[listener]
|
|
||||||
if exists == false {
|
|
||||||
panic("Attempting to unregister non-registered listener")
|
|
||||||
} else {
|
|
||||||
delete(node.listeners, listener)
|
|
||||||
}
|
|
||||||
node.listeners_lock.Unlock()
|
|
||||||
}
|
|
||||||
|
|
||||||
func (node * BaseNode) SignalChannel() chan GraphSignal {
|
|
||||||
return node.signal
|
|
||||||
}
|
|
||||||
|
|
||||||
// Create a new GraphSinal channel with a buffer of size buffer and register it to a node
|
|
||||||
func (node * BaseNode) UpdateChannel(buffer int) chan GraphSignal {
|
|
||||||
new_listener := make(chan GraphSignal, buffer)
|
|
||||||
node.RegisterChannel(new_listener)
|
|
||||||
return new_listener
|
|
||||||
}
|
|
||||||
|
|
||||||
// Propogate a signal starting at a node
|
|
||||||
func SendUpdate(ctx * GraphContext, node GraphNode, signal GraphSignal) {
|
|
||||||
if node == nil {
|
|
||||||
panic("Cannot start an update from no node")
|
|
||||||
}
|
|
||||||
|
|
||||||
ctx.Log.Logf("update", "UPDATE %s <- %s: %+v", node.ID(), signal.Source(), signal)
|
|
||||||
|
|
||||||
node.UpdateListeners(ctx, signal)
|
|
||||||
node.PropagateUpdate(ctx, signal)
|
|
||||||
}
|
|
||||||
|
|
@ -0,0 +1,66 @@
|
|||||||
|
package graphvent
|
||||||
|
|
||||||
|
import (
|
||||||
|
"reflect"
|
||||||
|
)
|
||||||
|
|
||||||
|
// A Listener extension provides a channel that can receive signals on a different thread
|
||||||
|
type ListenerExt struct {
|
||||||
|
Buffer int `gv:"buffer"`
|
||||||
|
Chan chan Signal
|
||||||
|
}
|
||||||
|
|
||||||
|
type LoadedSignal struct {
|
||||||
|
SignalHeader
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewLoadedSignal() *LoadedSignal {
|
||||||
|
return &LoadedSignal{
|
||||||
|
SignalHeader: NewSignalHeader(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type UnloadedSignal struct {
|
||||||
|
SignalHeader
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewUnloadedSignal() *UnloadedSignal {
|
||||||
|
return &UnloadedSignal{
|
||||||
|
SignalHeader: NewSignalHeader(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (ext *ListenerExt) Load(ctx *Context, node *Node) error {
|
||||||
|
ext.Chan = make(chan Signal, ext.Buffer)
|
||||||
|
ext.Chan <- NewLoadedSignal()
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (ext *ListenerExt) Unload(ctx *Context, node *Node) {
|
||||||
|
ext.Chan <- NewUnloadedSignal()
|
||||||
|
close(ext.Chan)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Create a new listener extension with a given buffer size
|
||||||
|
func NewListenerExt(buffer int) *ListenerExt {
|
||||||
|
return &ListenerExt{
|
||||||
|
Buffer: buffer,
|
||||||
|
Chan: make(chan Signal, buffer),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Send the signal to the channel, logging an overflow if it occurs
|
||||||
|
func (ext *ListenerExt) Process(ctx *Context, node *Node, source NodeID, signal Signal) ([]Message, Changes) {
|
||||||
|
ctx.Log.Logf("listener", "%s - %+v", node.ID, reflect.TypeOf(signal))
|
||||||
|
ctx.Log.Logf("listener_debug", "%s->%s - %+v", source, node.ID, signal)
|
||||||
|
select {
|
||||||
|
case ext.Chan <- signal:
|
||||||
|
default:
|
||||||
|
ctx.Log.Logf("listener", "LISTENER_OVERFLOW: %s", node.ID)
|
||||||
|
}
|
||||||
|
switch sig := signal.(type) {
|
||||||
|
case *StatusSignal:
|
||||||
|
ctx.Log.Logf("listener_status", "%s - %+v", sig.Source, sig.Fields)
|
||||||
|
}
|
||||||
|
return nil, nil
|
||||||
|
}
|
@ -1,444 +1,411 @@
|
|||||||
package graphvent
|
package graphvent
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"fmt"
|
"github.com/google/uuid"
|
||||||
"encoding/json"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
// LockHolderState is the interface that any node that wants to posses locks must implement
|
type ReqState byte
|
||||||
//
|
const (
|
||||||
// ReturnLock returns the node that held the lockable pointed to by ID before this node and
|
Unlocked = ReqState(0)
|
||||||
// removes the mapping from it's state, or nil if the lockable was unlocked previously
|
Unlocking = ReqState(1)
|
||||||
//
|
Locked = ReqState(2)
|
||||||
// AllowedToTakeLock returns true if the node pointed to by ID is allowed to take a lock from this node
|
Locking = ReqState(3)
|
||||||
//
|
AbortingLock = ReqState(4)
|
||||||
// RecordLockHolder records that lockable_id needs to be passed back to lock_holder
|
)
|
||||||
type LockHolderState interface {
|
|
||||||
NodeState
|
|
||||||
ReturnLock(lockable_id NodeID) GraphNode
|
|
||||||
AllowedToTakeLock(node_id NodeID, lockable_id NodeID) bool
|
|
||||||
RecordLockHolder(lockable_id NodeID, lock_holder GraphNode)
|
|
||||||
}
|
|
||||||
|
|
||||||
// LockableState is the interface that a lockables state must have to allow it to connect to the DAG
|
|
||||||
type LockableState interface {
|
|
||||||
LockHolderState
|
|
||||||
Requirements() []Lockable
|
|
||||||
AddRequirement(requirement Lockable)
|
|
||||||
Dependencies() []Lockable
|
|
||||||
AddDependency(dependency Lockable)
|
|
||||||
Owner() GraphNode
|
|
||||||
SetOwner(owner GraphNode)
|
|
||||||
}
|
|
||||||
|
|
||||||
type BaseLockHolderState struct {
|
|
||||||
delegation_map map[NodeID] GraphNode
|
|
||||||
}
|
|
||||||
|
|
||||||
type BaseLockHolderStateJSON struct {
|
|
||||||
Delegations map[NodeID]*NodeID `json:"delegations"`
|
|
||||||
}
|
|
||||||
|
|
||||||
func (state * BaseLockHolderState) MarshalJSON() ([]byte, error) {
|
|
||||||
delegations := map[NodeID]*NodeID{}
|
|
||||||
for lockable_id, node := range(state.delegation_map) {
|
|
||||||
if node == nil {
|
|
||||||
delegations[lockable_id] = nil
|
|
||||||
} else {
|
|
||||||
str := node.ID()
|
|
||||||
delegations[lockable_id] = &str
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return json.Marshal(&BaseLockHolderStateJSON{
|
|
||||||
Delegations: delegations,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
// BaseLockableStates are a minimum collection of variables for a basic implementation of a LockHolder
|
var ReqStateStrings = map[ReqState]string {
|
||||||
// Include in any state structs that should be lockable
|
Unlocked: "Unlocked",
|
||||||
type BaseLockableState struct {
|
Unlocking: "Unlocking",
|
||||||
BaseLockHolderState
|
Locked: "Locked",
|
||||||
name string
|
Locking: "Locking",
|
||||||
owner GraphNode
|
AbortingLock: "AbortingLock",
|
||||||
requirements []Lockable
|
|
||||||
dependencies []Lockable
|
|
||||||
}
|
}
|
||||||
|
|
||||||
type BaseLockableStateJSON struct {
|
func (state ReqState) String() string {
|
||||||
Name string `json:"name"`
|
str, mapped := ReqStateStrings[state]
|
||||||
Owner *NodeID `json:"owner"`
|
if mapped == false {
|
||||||
Dependencies []NodeID `json:"dependencies"`
|
return "UNKNOWN_REQSTATE"
|
||||||
Requirements []NodeID `json:"requirements"`
|
} else {
|
||||||
HolderState *BaseLockHolderState `json:"holder_state"`
|
return str
|
||||||
}
|
}
|
||||||
|
|
||||||
func (state * BaseLockableState) MarshalJSON() ([]byte, error) {
|
|
||||||
requirement_ids := make([]NodeID, len(state.requirements))
|
|
||||||
for i, requirement := range(state.requirements) {
|
|
||||||
requirement_ids[i] = requirement.ID()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
dependency_ids := make([]NodeID, len(state.dependencies))
|
|
||||||
for i, dependency := range(state.dependencies) {
|
|
||||||
dependency_ids[i] = dependency.ID()
|
|
||||||
}
|
|
||||||
|
|
||||||
var owner_id *NodeID = nil
|
type LockableExt struct{
|
||||||
if state.owner != nil {
|
State ReqState `gv:"state"`
|
||||||
new_str := state.owner.ID()
|
ReqID *uuid.UUID `gv:"req_id"`
|
||||||
owner_id = &new_str
|
Owner *NodeID `gv:"owner"`
|
||||||
}
|
PendingOwner *NodeID `gv:"pending_owner"`
|
||||||
|
Requirements map[NodeID]ReqState `gv:"requirements" node:"Lockable:"`
|
||||||
|
|
||||||
return json.Marshal(&BaseLockableStateJSON{
|
Locked map[NodeID]any
|
||||||
Name: state.name,
|
Unlocked map[NodeID]any
|
||||||
Owner: owner_id,
|
|
||||||
Dependencies: dependency_ids,
|
|
||||||
Requirements: requirement_ids,
|
|
||||||
HolderState: &state.BaseLockHolderState,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
func (state * BaseLockableState) Name() string {
|
Waiting WaitMap `gv:"waiting_locks" node:":Lockable"`
|
||||||
return state.name
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Locks cannot be passed between base lockables, so the answer to
|
func NewLockableExt(requirements []NodeID) *LockableExt {
|
||||||
// "who used to own this lock held by a base lockable" is always "nobody"
|
var reqs map[NodeID]ReqState = nil
|
||||||
func (state * BaseLockHolderState) ReturnLock(lockable_id NodeID) GraphNode {
|
var unlocked map[NodeID]any = map[NodeID]any{}
|
||||||
node, exists := state.delegation_map[lockable_id]
|
|
||||||
if exists == false {
|
|
||||||
panic("Attempted to take a get the original lock holder of a lockable we don't own")
|
|
||||||
}
|
|
||||||
delete(state.delegation_map, lockable_id)
|
|
||||||
return node
|
|
||||||
}
|
|
||||||
|
|
||||||
// Nothing can take a lock from a base lockable either
|
if len(requirements) != 0 {
|
||||||
func (state * BaseLockHolderState) AllowedToTakeLock(node_id NodeID, lockable_id NodeID) bool {
|
reqs = map[NodeID]ReqState{}
|
||||||
_, exists := state.delegation_map[lockable_id]
|
for _, req := range(requirements) {
|
||||||
if exists == false {
|
reqs[req] = Unlocked
|
||||||
panic ("Trying to give away lock we don't own")
|
unlocked[req] = nil
|
||||||
}
|
}
|
||||||
return false
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (state * BaseLockHolderState) RecordLockHolder(lockable_id NodeID, lock_holder GraphNode) {
|
return &LockableExt{
|
||||||
_, exists := state.delegation_map[lockable_id]
|
State: Unlocked,
|
||||||
if exists == true {
|
Owner: nil,
|
||||||
panic("Attempted to lock a lockable we're already holding(lock cycle)")
|
PendingOwner: nil,
|
||||||
}
|
Requirements: reqs,
|
||||||
|
Waiting: WaitMap{},
|
||||||
|
|
||||||
state.delegation_map[lockable_id] = lock_holder
|
Locked: map[NodeID]any{},
|
||||||
|
Unlocked: unlocked,
|
||||||
}
|
}
|
||||||
|
|
||||||
func (state * BaseLockableState) Owner() GraphNode {
|
|
||||||
return state.owner
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (state * BaseLockableState) SetOwner(owner GraphNode) {
|
func UnlockLockable(ctx *Context, node *Node) (uuid.UUID, error) {
|
||||||
state.owner = owner
|
signal := NewUnlockSignal()
|
||||||
|
messages := []Message{{node.ID, signal}}
|
||||||
|
return signal.ID(), ctx.Send(node, messages)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (state * BaseLockableState) Requirements() []Lockable {
|
func LockLockable(ctx *Context, node *Node) (uuid.UUID, error) {
|
||||||
return state.requirements
|
signal := NewLockSignal()
|
||||||
|
messages := []Message{{node.ID, signal}}
|
||||||
|
return signal.ID(), ctx.Send(node, messages)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (state * BaseLockableState) AddRequirement(requirement Lockable) {
|
func (ext *LockableExt) Load(ctx *Context, node *Node) error {
|
||||||
if requirement == nil {
|
ext.Locked = map[NodeID]any{}
|
||||||
panic("Will not connect nil to the DAG")
|
ext.Unlocked = map[NodeID]any{}
|
||||||
|
|
||||||
|
for id, state := range(ext.Requirements) {
|
||||||
|
if state == Unlocked {
|
||||||
|
ext.Unlocked[id] = nil
|
||||||
|
} else if state == Locked {
|
||||||
|
ext.Locked[id] = nil
|
||||||
}
|
}
|
||||||
state.requirements = append(state.requirements, requirement)
|
|
||||||
}
|
}
|
||||||
|
return nil
|
||||||
func (state * BaseLockableState) Dependencies() []Lockable {
|
|
||||||
return state.dependencies
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (state * BaseLockableState) AddDependency(dependency Lockable) {
|
func (ext *LockableExt) Unload(ctx *Context, node *Node) {
|
||||||
if dependency == nil {
|
return
|
||||||
panic("Will not connect nil to the DAG")
|
|
||||||
}
|
}
|
||||||
|
|
||||||
state.dependencies = append(state.dependencies, dependency)
|
// Handle link signal by adding/removing the requested NodeID
|
||||||
}
|
// returns an error if the node is not unlocked
|
||||||
|
func (ext *LockableExt) HandleLinkSignal(ctx *Context, node *Node, source NodeID, signal *LinkSignal) ([]Message, Changes) {
|
||||||
|
var messages []Message = nil
|
||||||
|
var changes Changes = nil
|
||||||
|
|
||||||
func NewLockHolderState() BaseLockHolderState {
|
switch ext.State {
|
||||||
return BaseLockHolderState{
|
case Unlocked:
|
||||||
delegation_map: map[NodeID]GraphNode{},
|
switch signal.Action {
|
||||||
}
|
case "add":
|
||||||
|
_, exists := ext.Requirements[signal.NodeID]
|
||||||
|
if exists == true {
|
||||||
|
messages = append(messages, Message{source, NewErrorSignal(signal.ID(), "already_requirement")})
|
||||||
|
} else {
|
||||||
|
if ext.Requirements == nil {
|
||||||
|
ext.Requirements = map[NodeID]ReqState{}
|
||||||
}
|
}
|
||||||
|
ext.Requirements[signal.NodeID] = Unlocked
|
||||||
func LinkLockables(ctx * GraphContext, lockable Lockable, requirements []Lockable) error {
|
changes = append(changes, "requirements")
|
||||||
if lockable == nil {
|
messages = append(messages, Message{source, NewSuccessSignal(signal.ID())})
|
||||||
return fmt.Errorf("LOCKABLE_LINK_ERR: Will not link Lockables to nil as requirements")
|
|
||||||
}
|
}
|
||||||
|
case "remove":
|
||||||
for _, requirement := range(requirements) {
|
_, exists := ext.Requirements[signal.NodeID]
|
||||||
if requirement == nil {
|
if exists == false {
|
||||||
return fmt.Errorf("LOCKABLE_LINK_ERR: Will not link nil to a Lockable as a requirement")
|
messages = append(messages, Message{source, NewErrorSignal(signal.ID(), "not_requirement")})
|
||||||
|
} else {
|
||||||
|
delete(ext.Requirements, signal.NodeID)
|
||||||
|
changes = append(changes, "requirements")
|
||||||
|
messages = append(messages, Message{source, NewSuccessSignal(signal.ID())})
|
||||||
}
|
}
|
||||||
|
default:
|
||||||
if lockable.ID() == requirement.ID() {
|
messages = append(messages, Message{source, NewErrorSignal(signal.ID(), "unknown_action")})
|
||||||
return fmt.Errorf("LOCKABLE_LINK_ERR: cannot link %s to itself", lockable.ID())
|
|
||||||
}
|
}
|
||||||
|
default:
|
||||||
|
messages = append(messages, Message{source, NewErrorSignal(signal.ID(), "not_unlocked: %s", ext.State)})
|
||||||
}
|
}
|
||||||
|
|
||||||
nodes := make([]GraphNode, len(requirements) + 1)
|
return messages, changes
|
||||||
nodes[0] = lockable
|
|
||||||
for i, node := range(requirements) {
|
|
||||||
nodes[i+1] = node
|
|
||||||
}
|
}
|
||||||
_, err := UpdateStates(ctx, nodes, func(states []NodeState) ([]NodeState, interface{}, error) {
|
|
||||||
// Check that all the requirements can be added
|
|
||||||
lockable_state := states[0].(LockableState)
|
|
||||||
for i, requirement := range(requirements) {
|
|
||||||
requirement_state := states[i+1].(LockableState)
|
|
||||||
|
|
||||||
|
// Handle an UnlockSignal by either transitioning to Unlocked state,
|
||||||
|
// sending unlock signals to requirements, or returning an error signal
|
||||||
|
func (ext *LockableExt) HandleUnlockSignal(ctx *Context, node *Node, source NodeID, signal *UnlockSignal) ([]Message, Changes) {
|
||||||
|
var messages []Message = nil
|
||||||
|
var changes Changes = nil
|
||||||
|
|
||||||
if checkIfRequirement(ctx, lockable.ID(), requirement_state, requirement.ID()) == true {
|
switch ext.State {
|
||||||
return nil, nil, fmt.Errorf("LOCKABLE_LINK_ERR: %s is a dependency of %s so cannot link as requirement", requirement.ID(), lockable.ID())
|
case Locked:
|
||||||
}
|
if source != *ext.Owner {
|
||||||
|
messages = append(messages, Message{source, NewErrorSignal(signal.Id, "not_owner")})
|
||||||
|
} else {
|
||||||
|
if len(ext.Requirements) == 0 {
|
||||||
|
changes = append(changes, "state", "owner", "pending_owner")
|
||||||
|
|
||||||
if checkIfRequirement(ctx, requirement.ID(), lockable_state, lockable.ID()) == true {
|
ext.Owner = nil
|
||||||
return nil, nil, fmt.Errorf("LOCKABLE_LINK_ERR: %s is a dependency of %s so cannot link as dependency again", lockable.ID(), requirement.ID())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
// Update the states of the requirements
|
|
||||||
for i, requirement := range(requirements) {
|
|
||||||
requirement_state := states[i+1].(LockableState)
|
|
||||||
requirement_state.AddDependency(lockable)
|
|
||||||
lockable_state.AddRequirement(requirement)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Return no error
|
ext.PendingOwner = nil
|
||||||
return states, nil, nil
|
|
||||||
})
|
|
||||||
|
|
||||||
return err
|
ext.State = Unlocked
|
||||||
}
|
|
||||||
|
|
||||||
func NewBaseLockableState(name string) BaseLockableState {
|
messages = append(messages, Message{source, NewSuccessSignal(signal.Id)})
|
||||||
state := BaseLockableState{
|
} else {
|
||||||
BaseLockHolderState: NewLockHolderState(),
|
changes = append(changes, "state", "waiting", "requirements", "pending_owner")
|
||||||
name: name,
|
|
||||||
owner: nil,
|
|
||||||
requirements: []Lockable{},
|
|
||||||
dependencies: []Lockable{},
|
|
||||||
}
|
|
||||||
|
|
||||||
return state
|
ext.PendingOwner = nil
|
||||||
}
|
|
||||||
|
|
||||||
type Lockable interface {
|
ext.ReqID = &signal.Id
|
||||||
GraphNode
|
|
||||||
// Called when locking the node to allow for custom lock behaviour
|
ext.State = Unlocking
|
||||||
Lock(node GraphNode, state LockableState) error
|
for id := range(ext.Requirements) {
|
||||||
// Called when unlocking the node to allow for custom lock behaviour
|
unlock_signal := NewUnlockSignal()
|
||||||
Unlock(node GraphNode, state LockableState) error
|
|
||||||
}
|
|
||||||
|
|
||||||
func (lockable * BaseLockable) PropagateUpdate(ctx * GraphContext, signal GraphSignal) {
|
ext.Waiting[unlock_signal.Id] = id
|
||||||
UseStates(ctx, []GraphNode{lockable}, func(states []NodeState) (interface{}, error){
|
ext.Requirements[id] = Unlocking
|
||||||
lockable_state := states[0].(LockableState)
|
|
||||||
if signal.Direction() == Up {
|
messages = append(messages, Message{id, unlock_signal})
|
||||||
// Child->Parent, lockable updates dependency lockables
|
|
||||||
owner_sent := false
|
|
||||||
for _, dependency := range lockable_state.Dependencies() {
|
|
||||||
SendUpdate(ctx, dependency, signal)
|
|
||||||
if lockable_state.Owner() != nil {
|
|
||||||
if dependency.ID() != lockable_state.Owner().ID() {
|
|
||||||
owner_sent = true
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if lockable_state.Owner() != nil && owner_sent == false {
|
default:
|
||||||
SendUpdate(ctx, lockable_state.Owner(), signal)
|
messages = append(messages, Message{source, NewErrorSignal(signal.Id, "not_locked")})
|
||||||
}
|
}
|
||||||
} else if signal.Direction() == Down {
|
|
||||||
// Parent->Child, lockable updates lock holder
|
return messages, changes
|
||||||
for _, requirement := range(lockable_state.Requirements()) {
|
|
||||||
SendUpdate(ctx, requirement, signal)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
} else if signal.Direction() == Direct {
|
// Handle a LockSignal by either transitioning to a locked state,
|
||||||
|
// sending lock signals to requirements, or returning an error signal
|
||||||
|
func (ext *LockableExt) HandleLockSignal(ctx *Context, node *Node, source NodeID, signal *LockSignal) ([]Message, Changes) {
|
||||||
|
var messages []Message = nil
|
||||||
|
var changes Changes = nil
|
||||||
|
|
||||||
|
switch ext.State {
|
||||||
|
case Unlocked:
|
||||||
|
if len(ext.Requirements) == 0 {
|
||||||
|
changes = append(changes, "state", "owner", "pending_owner")
|
||||||
|
|
||||||
|
ext.Owner = &source
|
||||||
|
|
||||||
|
ext.PendingOwner = &source
|
||||||
|
|
||||||
|
ext.State = Locked
|
||||||
|
messages = append(messages, Message{source, NewSuccessSignal(signal.Id)})
|
||||||
} else {
|
} else {
|
||||||
panic(fmt.Sprintf("Invalid signal direction: %d", signal.Direction()))
|
changes = append(changes, "state", "requirements", "waiting", "pending_owner")
|
||||||
}
|
|
||||||
return nil, nil
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
func checkIfRequirement(ctx * GraphContext, r_id NodeID, cur LockableState, cur_id NodeID) bool {
|
ext.PendingOwner = &source
|
||||||
for _, c := range(cur.Requirements()) {
|
|
||||||
if c.ID() == r_id {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
val, _ := UseStates(ctx, []GraphNode{c}, func(states []NodeState) (interface{}, error) {
|
|
||||||
requirement_state := states[0].(LockableState)
|
|
||||||
return checkIfRequirement(ctx, cur_id, requirement_state, c.ID()), nil
|
|
||||||
})
|
|
||||||
|
|
||||||
is_requirement := val.(bool)
|
ext.ReqID = &signal.Id
|
||||||
if is_requirement {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return false
|
ext.State = Locking
|
||||||
}
|
for id := range(ext.Requirements) {
|
||||||
|
lock_signal := NewLockSignal()
|
||||||
|
|
||||||
|
ext.Waiting[lock_signal.Id] = id
|
||||||
|
ext.Requirements[id] = Locking
|
||||||
|
|
||||||
func UnlockLockable(ctx * GraphContext, lockable Lockable, node GraphNode, node_state LockHolderState) error {
|
messages = append(messages, Message{id, lock_signal})
|
||||||
if node == nil || lockable == nil{
|
|
||||||
panic("Cannot unlock without a specified node and lockable")
|
|
||||||
}
|
}
|
||||||
_, err := UpdateStates(ctx, []GraphNode{lockable}, func(states []NodeState) ([]NodeState, interface{}, error) {
|
|
||||||
if lockable.ID() == node.ID() {
|
|
||||||
if node_state != nil {
|
|
||||||
panic("node_state must be nil if unlocking lockable from itself")
|
|
||||||
}
|
}
|
||||||
node_state = states[0].(LockHolderState)
|
default:
|
||||||
|
messages = append(messages, Message{source, NewErrorSignal(signal.Id, "not_unlocked: %s", ext.State)})
|
||||||
}
|
}
|
||||||
lockable_state := states[0].(LockableState)
|
|
||||||
|
|
||||||
if lockable_state.Owner() == nil {
|
return messages, changes
|
||||||
return nil, nil, fmt.Errorf("Lockable already unlocked")
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if lockable_state.Owner().ID() != node.ID() {
|
// Handle an error signal by aborting the lock, or retrying the unlock
|
||||||
return nil, nil, fmt.Errorf("Lockable %s not locked by %s", lockable.ID(), node.ID())
|
func (ext *LockableExt) HandleErrorSignal(ctx *Context, node *Node, source NodeID, signal *ErrorSignal) ([]Message, Changes) {
|
||||||
}
|
var messages []Message = nil
|
||||||
|
var changes Changes = nil
|
||||||
|
|
||||||
var lock_err error = nil
|
id, waiting := ext.Waiting[signal.ReqID]
|
||||||
for _, requirement := range(lockable_state.Requirements()) {
|
if waiting == true {
|
||||||
var err error = nil
|
delete(ext.Waiting, signal.ReqID)
|
||||||
err = UnlockLockable(ctx, requirement, node, node_state)
|
changes = append(changes, "waiting")
|
||||||
if err != nil {
|
|
||||||
lock_err = err
|
|
||||||
break
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if lock_err != nil {
|
switch ext.State {
|
||||||
return nil, nil, fmt.Errorf("Lockable %s failed to unlock: %e", lockable.ID(), lock_err)
|
case Locking:
|
||||||
}
|
changes = append(changes, "state", "requirements")
|
||||||
|
|
||||||
|
ext.Requirements[id] = Unlocked
|
||||||
|
|
||||||
new_owner := node_state.ReturnLock(lockable.ID())
|
unlocked := 0
|
||||||
lockable_state.SetOwner(new_owner)
|
for req_id, req_state := range(ext.Requirements) {
|
||||||
err := lockable.Unlock(node, lockable_state)
|
// Unlock locked requirements, and count unlocked requirements
|
||||||
if err != nil {
|
switch req_state {
|
||||||
return nil, nil, fmt.Errorf("Lockable %s failed custom Unlock: %e", lockable.ID(), err)
|
case Locked:
|
||||||
|
unlock_signal := NewUnlockSignal()
|
||||||
|
|
||||||
|
ext.Waiting[unlock_signal.Id] = req_id
|
||||||
|
ext.Requirements[req_id] = Unlocking
|
||||||
|
|
||||||
|
messages = append(messages, Message{req_id, unlock_signal})
|
||||||
|
case Unlocked:
|
||||||
|
unlocked += 1
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if lockable_state.Owner() == nil {
|
if unlocked == len(ext.Requirements) {
|
||||||
ctx.Log.Logf("lockable", "LOCKABLE_UNLOCK: %s unlocked %s", node.ID(), lockable.ID())
|
changes = append(changes, "owner", "state")
|
||||||
|
ext.State = Unlocked
|
||||||
|
ext.Owner = nil
|
||||||
} else {
|
} else {
|
||||||
ctx.Log.Logf("lockable", "LOCKABLE_UNLOCK: %s passed lock of %s back to %s", node.ID(), lockable.ID(), lockable_state.Owner().ID())
|
changes = append(changes, "state")
|
||||||
|
ext.State = AbortingLock
|
||||||
}
|
}
|
||||||
|
|
||||||
return []NodeState{lockable_state}, nil, nil
|
case Unlocking:
|
||||||
})
|
unlock_signal := NewUnlockSignal()
|
||||||
|
ext.Waiting[unlock_signal.Id] = id
|
||||||
|
messages = append(messages, Message{id, unlock_signal})
|
||||||
|
|
||||||
return err
|
case AbortingLock:
|
||||||
}
|
req_state := ext.Requirements[id]
|
||||||
|
// Mark failed lock as Unlocked, or retry unlock
|
||||||
|
switch req_state {
|
||||||
|
case Locking:
|
||||||
|
ext.Requirements[id] = Unlocked
|
||||||
|
|
||||||
func LockLockable(ctx * GraphContext, lockable Lockable, node GraphNode, node_state LockHolderState) error {
|
// Check if all requirements unlocked now
|
||||||
if node == nil || lockable == nil {
|
unlocked := 0
|
||||||
return fmt.Errorf("Cannot lock without a specified node and lockable")
|
for _, req_state := range(ext.Requirements) {
|
||||||
|
if req_state == Unlocked {
|
||||||
|
unlocked += 1
|
||||||
|
}
|
||||||
}
|
}
|
||||||
ctx.Log.Logf("lockable", "LOCKING: %s from %s", lockable.ID(), node.ID())
|
|
||||||
|
|
||||||
_, err := UpdateStates(ctx, []GraphNode{lockable}, func(states []NodeState) ([]NodeState, interface{}, error) {
|
if unlocked == len(ext.Requirements) {
|
||||||
if lockable.ID() == node.ID() {
|
changes = append(changes, "owner", "state")
|
||||||
if node_state != nil {
|
ext.State = Unlocked
|
||||||
return nil, nil, fmt.Errorf("node_state must be nil if locking lockable from itself")
|
ext.Owner = nil
|
||||||
|
}
|
||||||
|
case Unlocking:
|
||||||
|
// Handle error for unlocking requirement while unlocking by retrying unlock
|
||||||
|
unlock_signal := NewUnlockSignal()
|
||||||
|
ext.Waiting[unlock_signal.Id] = id
|
||||||
|
messages = append(messages, Message{id, unlock_signal})
|
||||||
|
}
|
||||||
}
|
}
|
||||||
node_state = states[0].(LockHolderState)
|
|
||||||
}
|
}
|
||||||
lockable_state := states[0].(LockableState)
|
|
||||||
if lockable_state.Owner() != nil {
|
|
||||||
var lock_pass_allowed bool = false
|
|
||||||
|
|
||||||
if lockable_state.Owner().ID() == lockable.ID() {
|
return messages, changes
|
||||||
lock_pass_allowed = lockable_state.AllowedToTakeLock(node.ID(), lockable.ID())
|
|
||||||
} else {
|
|
||||||
tmp, _ := UseStates(ctx, []GraphNode{lockable_state.Owner()}, func(states []NodeState)(interface{}, error){
|
|
||||||
return states[0].(LockHolderState).AllowedToTakeLock(node.ID(), lockable.ID()), nil
|
|
||||||
})
|
|
||||||
lock_pass_allowed = tmp.(bool)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Handle a success signal by checking if all requirements have been locked/unlocked
|
||||||
|
func (ext *LockableExt) HandleSuccessSignal(ctx *Context, node *Node, source NodeID, signal *SuccessSignal) ([]Message, Changes) {
|
||||||
|
var messages []Message = nil
|
||||||
|
var changes Changes = nil
|
||||||
|
|
||||||
if lock_pass_allowed == false {
|
id, waiting := ext.Waiting[signal.ReqID]
|
||||||
return nil, nil, fmt.Errorf("%s is not allowed to take a lock from %s", node.ID(), lockable_state.Owner().ID())
|
if waiting == true {
|
||||||
}
|
delete(ext.Waiting, signal.ReqID)
|
||||||
}
|
changes = append(changes, "waiting")
|
||||||
|
|
||||||
|
switch ext.State {
|
||||||
|
case Locking:
|
||||||
|
ext.Requirements[id] = Locked
|
||||||
|
ext.Locked[id] = nil
|
||||||
|
delete(ext.Unlocked, id)
|
||||||
|
|
||||||
err := lockable.Lock(node, lockable_state)
|
if len(ext.Locked) == len(ext.Requirements) {
|
||||||
if err != nil {
|
ctx.Log.Logf("lockable", "%s FULL_LOCK: %d", node.ID, len(ext.Locked))
|
||||||
return nil, nil, fmt.Errorf("Failed to lock lockable: %e", err)
|
changes = append(changes, "state", "owner", "req_id")
|
||||||
|
ext.State = Locked
|
||||||
|
|
||||||
|
ext.Owner = ext.PendingOwner
|
||||||
|
|
||||||
|
messages = append(messages, Message{*ext.Owner, NewSuccessSignal(*ext.ReqID)})
|
||||||
|
ext.ReqID = nil
|
||||||
|
} else {
|
||||||
|
ctx.Log.Logf("lockable", "%s PARTIAL_LOCK: %d/%d", node.ID, len(ext.Locked), len(ext.Requirements))
|
||||||
}
|
}
|
||||||
|
case AbortingLock:
|
||||||
|
req_state := ext.Requirements[id]
|
||||||
|
switch req_state {
|
||||||
|
case Locking:
|
||||||
|
ext.Requirements[id] = Unlocking
|
||||||
|
unlock_signal := NewUnlockSignal()
|
||||||
|
ext.Waiting[unlock_signal.Id] = id
|
||||||
|
messages = append(messages, Message{id, unlock_signal})
|
||||||
|
case Unlocking:
|
||||||
|
ext.Requirements[id] = Unlocked
|
||||||
|
ext.Unlocked[id] = nil
|
||||||
|
delete(ext.Locked, id)
|
||||||
|
|
||||||
var lock_err error = nil
|
unlocked := 0
|
||||||
locked_requirements := []Lockable{}
|
for _, req_state := range(ext.Requirements) {
|
||||||
for _, requirement := range(lockable_state.Requirements()) {
|
switch req_state {
|
||||||
err = LockLockable(ctx, requirement, node, node_state)
|
case Unlocked:
|
||||||
if err != nil {
|
unlocked += 1
|
||||||
lock_err = err
|
|
||||||
break
|
|
||||||
}
|
}
|
||||||
locked_requirements = append(locked_requirements, requirement)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if lock_err != nil {
|
if unlocked == len(ext.Requirements) {
|
||||||
for _, locked_lockable := range(locked_requirements) {
|
changes = append(changes, "state", "pending_owner", "req_id")
|
||||||
err = UnlockLockable(ctx, locked_lockable, node, node_state)
|
|
||||||
if err != nil {
|
messages = append(messages, Message{*ext.PendingOwner, NewErrorSignal(*ext.ReqID, "not_unlocked: %s", ext.State)})
|
||||||
panic(err)
|
ext.State = Unlocked
|
||||||
}
|
ext.ReqID = nil
|
||||||
|
ext.PendingOwner = nil
|
||||||
}
|
}
|
||||||
return nil, nil, fmt.Errorf("Lockable failed to lock: %e", lock_err)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
old_owner := lockable_state.Owner()
|
|
||||||
lockable_state.SetOwner(node)
|
|
||||||
node_state.RecordLockHolder(lockable.ID(), old_owner)
|
|
||||||
|
|
||||||
if old_owner == nil {
|
case Unlocking:
|
||||||
ctx.Log.Logf("lockable", "LOCKABLE_LOCK: %s locked %s", node.ID(), lockable.ID())
|
ext.Requirements[id] = Unlocked
|
||||||
} else {
|
ext.Unlocked[id] = Unlocked
|
||||||
ctx.Log.Logf("lockable", "LOCKABLE_LOCK: %s took lock of %s from %s", node.ID(), lockable.ID(), old_owner.ID())
|
delete(ext.Locked, id)
|
||||||
}
|
|
||||||
|
|
||||||
return []NodeState{lockable_state}, nil, nil
|
if len(ext.Unlocked) == len(ext.Requirements) {
|
||||||
})
|
changes = append(changes, "state", "owner", "req_id")
|
||||||
|
|
||||||
return err
|
messages = append(messages, Message{*ext.Owner, NewSuccessSignal(*ext.ReqID)})
|
||||||
|
ext.State = Unlocked
|
||||||
|
ext.ReqID = nil
|
||||||
|
ext.Owner = nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// BaseLockables represent simple lockables in the DAG that can be used to create a hierarchy of locks that store names
|
|
||||||
type BaseLockable struct {
|
|
||||||
BaseNode
|
|
||||||
}
|
}
|
||||||
|
|
||||||
//BaseLockables don't check anything special when locking/unlocking
|
|
||||||
func (lockable * BaseLockable) Lock(node GraphNode, state LockableState) error {
|
|
||||||
return nil
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (lockable * BaseLockable) Unlock(node GraphNode, state LockableState) error {
|
return messages, changes
|
||||||
return nil
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewLockable(ctx * GraphContext, name string, requirements []Lockable) (* BaseLockable, error) {
|
func (ext *LockableExt) Process(ctx *Context, node *Node, source NodeID, signal Signal) ([]Message, Changes) {
|
||||||
state := NewBaseLockableState(name)
|
var messages []Message = nil
|
||||||
lockable := &BaseLockable{
|
var changes Changes = nil
|
||||||
BaseNode: NewNode(ctx, RandID(), &state),
|
|
||||||
}
|
|
||||||
|
|
||||||
err := LinkLockables(ctx, lockable, requirements)
|
switch sig := signal.(type) {
|
||||||
if err != nil {
|
case *StatusSignal:
|
||||||
return nil, err
|
// Forward StatusSignals up to the owner(unless that would be a cycle)
|
||||||
|
if ext.Owner != nil {
|
||||||
|
if *ext.Owner != node.ID {
|
||||||
|
messages = append(messages, Message{*ext.Owner, signal})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
case *LinkSignal:
|
||||||
|
messages, changes = ext.HandleLinkSignal(ctx, node, source, sig)
|
||||||
|
case *LockSignal:
|
||||||
|
messages, changes = ext.HandleLockSignal(ctx, node, source, sig)
|
||||||
|
case *UnlockSignal:
|
||||||
|
messages, changes = ext.HandleUnlockSignal(ctx, node, source, sig)
|
||||||
|
case *ErrorSignal:
|
||||||
|
messages, changes = ext.HandleErrorSignal(ctx, node, source, sig)
|
||||||
|
case *SuccessSignal:
|
||||||
|
messages, changes = ext.HandleSuccessSignal(ctx, node, source, sig)
|
||||||
}
|
}
|
||||||
|
|
||||||
return lockable, nil
|
return messages, changes
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -0,0 +1,97 @@
|
|||||||
|
package graphvent
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"github.com/rs/zerolog"
|
||||||
|
"os"
|
||||||
|
"sync"
|
||||||
|
"encoding/json"
|
||||||
|
)
|
||||||
|
|
||||||
|
// A Logger is passed around to record events happening to components enabled by SetComponents
|
||||||
|
type Logger interface {
|
||||||
|
SetComponents(components []string) error
|
||||||
|
// Log a formatted string
|
||||||
|
Logf(component string, format string, items ... interface{})
|
||||||
|
// Log a map of attributes and a format string
|
||||||
|
Logm(component string, fields map[string]interface{}, format string, items ... interface{})
|
||||||
|
// Log a structure to a file by marshalling and unmarshalling the json
|
||||||
|
Logj(component string, s interface{}, format string, items ... interface{})
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewConsoleLogger(components []string) *ConsoleLogger {
|
||||||
|
logger := &ConsoleLogger{
|
||||||
|
loggers: map[string]zerolog.Logger{},
|
||||||
|
components: []string{},
|
||||||
|
}
|
||||||
|
|
||||||
|
logger.SetComponents(components)
|
||||||
|
|
||||||
|
return logger
|
||||||
|
}
|
||||||
|
|
||||||
|
// A ConsoleLogger logs to stdout
|
||||||
|
type ConsoleLogger struct {
|
||||||
|
loggers map[string]zerolog.Logger
|
||||||
|
components_lock sync.Mutex
|
||||||
|
components []string
|
||||||
|
}
|
||||||
|
|
||||||
|
func (logger * ConsoleLogger) SetComponents(components []string) error {
|
||||||
|
logger.components_lock.Lock()
|
||||||
|
defer logger.components_lock.Unlock()
|
||||||
|
|
||||||
|
component_enabled := func (component string) bool {
|
||||||
|
for _, c := range(components) {
|
||||||
|
if c == component {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
for c := range(logger.loggers) {
|
||||||
|
if component_enabled(c) == false {
|
||||||
|
delete(logger.loggers, c)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, c := range(components) {
|
||||||
|
_, exists := logger.loggers[c]
|
||||||
|
if component_enabled(c) == true && exists == false {
|
||||||
|
logger.loggers[c] = zerolog.New(os.Stdout).With().Timestamp().Str("component", c).Logger()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (logger * ConsoleLogger) Logm(component string, fields map[string]interface{}, format string, items ... interface{}) {
|
||||||
|
l, exists := logger.loggers[component]
|
||||||
|
if exists == true {
|
||||||
|
log := l.Log()
|
||||||
|
for key, value := range(fields) {
|
||||||
|
log = log.Str(key, fmt.Sprintf("%+v", value))
|
||||||
|
}
|
||||||
|
log.Msg(fmt.Sprintf(format, items...))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (logger * ConsoleLogger) Logf(component string, format string, items ... interface{}) {
|
||||||
|
l, exists := logger.loggers[component]
|
||||||
|
if exists == true {
|
||||||
|
l.Log().Msg(fmt.Sprintf(format, items...))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (logger * ConsoleLogger) Logj(component string, s interface{}, format string, items ... interface{}) {
|
||||||
|
m := map[string]interface{}{}
|
||||||
|
ser, err := json.Marshal(s)
|
||||||
|
if err != nil {
|
||||||
|
panic("LOG_MARSHAL_ERR")
|
||||||
|
}
|
||||||
|
err = json.Unmarshal(ser, &m)
|
||||||
|
if err != nil {
|
||||||
|
panic("LOG_UNMARSHAL_ERR")
|
||||||
|
}
|
||||||
|
logger.Logm(component, m, format, items...)
|
||||||
|
}
|
@ -0,0 +1,68 @@
|
|||||||
|
package graphvent
|
||||||
|
|
||||||
|
type Message struct {
|
||||||
|
Node NodeID
|
||||||
|
Signal Signal
|
||||||
|
}
|
||||||
|
|
||||||
|
type MessageQueue struct {
|
||||||
|
out chan<- Message
|
||||||
|
in <-chan Message
|
||||||
|
buffer []Message
|
||||||
|
write_cursor int
|
||||||
|
read_cursor int
|
||||||
|
}
|
||||||
|
|
||||||
|
func (queue *MessageQueue) ProcessIncoming(message Message) {
|
||||||
|
if (queue.write_cursor + 1) == queue.read_cursor || ((queue.write_cursor + 1) == len(queue.buffer) && queue.read_cursor == 0) {
|
||||||
|
new_buffer := make([]Message, len(queue.buffer) * 2)
|
||||||
|
|
||||||
|
copy(new_buffer, queue.buffer[queue.read_cursor:])
|
||||||
|
first_chunk := len(queue.buffer) - queue.read_cursor
|
||||||
|
copy(new_buffer[first_chunk:], queue.buffer[0:queue.write_cursor])
|
||||||
|
|
||||||
|
queue.write_cursor = len(queue.buffer) - 1
|
||||||
|
queue.read_cursor = 0
|
||||||
|
queue.buffer = new_buffer
|
||||||
|
}
|
||||||
|
|
||||||
|
queue.buffer[queue.write_cursor] = message
|
||||||
|
queue.write_cursor += 1
|
||||||
|
if queue.write_cursor >= len(queue.buffer) {
|
||||||
|
queue.write_cursor = 0
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewMessageQueue(initial int) (chan<- Message, <-chan Message) {
|
||||||
|
in := make(chan Message, 0)
|
||||||
|
out := make(chan Message, 0)
|
||||||
|
|
||||||
|
queue := MessageQueue{
|
||||||
|
out: out,
|
||||||
|
in: in,
|
||||||
|
buffer: make([]Message, initial),
|
||||||
|
write_cursor: 0,
|
||||||
|
read_cursor: 0,
|
||||||
|
}
|
||||||
|
|
||||||
|
go func(queue *MessageQueue) {
|
||||||
|
for true {
|
||||||
|
if queue.write_cursor != queue.read_cursor {
|
||||||
|
select {
|
||||||
|
case incoming := <-queue.in:
|
||||||
|
queue.ProcessIncoming(incoming)
|
||||||
|
case queue.out <- queue.buffer[queue.read_cursor]:
|
||||||
|
queue.read_cursor += 1
|
||||||
|
if queue.read_cursor >= len(queue.buffer) {
|
||||||
|
queue.read_cursor = 0
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
message := <-queue.in
|
||||||
|
queue.ProcessIncoming(message)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}(&queue)
|
||||||
|
|
||||||
|
return in, out
|
||||||
|
}
|
@ -0,0 +1,35 @@
|
|||||||
|
package graphvent
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/binary"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func sendBatch(start, end uint64, in chan<- Message) {
|
||||||
|
for i := start; i <= end; i++ {
|
||||||
|
var id NodeID
|
||||||
|
binary.BigEndian.PutUint64(id[:], i)
|
||||||
|
in <- Message{id, nil}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestMessageQueue(t *testing.T) {
|
||||||
|
in, out := NewMessageQueue(10)
|
||||||
|
|
||||||
|
for i := uint64(0); i < 1000; i++ {
|
||||||
|
go sendBatch(1000*i, (1000*(i+1))-1, in)
|
||||||
|
}
|
||||||
|
|
||||||
|
seen := map[NodeID]any{}
|
||||||
|
for i := uint64(0); i < 1000*1000; i++ {
|
||||||
|
read := <-out
|
||||||
|
_, already_seen := seen[read.Node]
|
||||||
|
if already_seen {
|
||||||
|
t.Fatalf("Signal %d had duplicate NodeID %s", i, read.Node)
|
||||||
|
} else {
|
||||||
|
seen[read.Node] = nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
t.Logf("Processed 1M signals through queue")
|
||||||
|
}
|
@ -0,0 +1,401 @@
|
|||||||
|
package graphvent
|
||||||
|
|
||||||
|
import (
|
||||||
|
"crypto/ed25519"
|
||||||
|
"crypto/sha512"
|
||||||
|
"fmt"
|
||||||
|
"reflect"
|
||||||
|
"sync/atomic"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
_ "github.com/dgraph-io/badger/v3"
|
||||||
|
"github.com/google/uuid"
|
||||||
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
// Base NodeID, used as a special value
|
||||||
|
ZeroUUID = uuid.UUID{}
|
||||||
|
ZeroID = NodeID(ZeroUUID)
|
||||||
|
)
|
||||||
|
|
||||||
|
// A NodeID uniquely identifies a Node
|
||||||
|
type NodeID uuid.UUID
|
||||||
|
func (id NodeID) MarshalBinary() ([]byte, error) {
|
||||||
|
return (uuid.UUID)(id).MarshalBinary()
|
||||||
|
}
|
||||||
|
func (id *NodeID) UnmarshalBinary(data []byte) error {
|
||||||
|
return (*uuid.UUID)(id).UnmarshalBinary(data)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (id NodeID) String() string {
|
||||||
|
return (uuid.UUID)(id).String()
|
||||||
|
}
|
||||||
|
func IDFromBytes(bytes []byte) (NodeID, error) {
|
||||||
|
id, err := uuid.FromBytes(bytes)
|
||||||
|
return NodeID(id), err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (id NodeID) MarshalText() ([]byte, error) {
|
||||||
|
return []byte(id.String()), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (id *NodeID) UnmarshalText(text []byte) error {
|
||||||
|
parsed, err := ParseID(string(text))
|
||||||
|
*id = parsed
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
// Parse an ID from a string
|
||||||
|
func ParseID(str string) (NodeID, error) {
|
||||||
|
id_uuid, err := uuid.Parse(str)
|
||||||
|
if err != nil {
|
||||||
|
return NodeID{}, err
|
||||||
|
}
|
||||||
|
return NodeID(id_uuid), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Generate a random NodeID
|
||||||
|
func RandID() NodeID {
|
||||||
|
return NodeID(uuid.New())
|
||||||
|
}
|
||||||
|
|
||||||
|
// A QueuedSignal is a Signal that has been Queued to trigger at a set time
|
||||||
|
type QueuedSignal struct {
|
||||||
|
Signal `gv:"signal"`
|
||||||
|
time.Time `gv:"time"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (q QueuedSignal) String() string {
|
||||||
|
return fmt.Sprintf("%+v@%s", reflect.TypeOf(q.Signal), q.Time)
|
||||||
|
}
|
||||||
|
|
||||||
|
type WaitMap map[uuid.UUID]NodeID
|
||||||
|
|
||||||
|
const NODE_INITIAL_QUEUE_SIZE = 2
|
||||||
|
|
||||||
|
// Nodes represent a group of extensions that can be collectively addressed
|
||||||
|
type Node struct {
|
||||||
|
Key ed25519.PrivateKey `gv:"key"`
|
||||||
|
ID NodeID
|
||||||
|
Type NodeType `gv:"type"`
|
||||||
|
|
||||||
|
Extensions map[ExtType]Extension
|
||||||
|
|
||||||
|
// Channel for this node to receive messages from the Context
|
||||||
|
SendChan chan<- Message
|
||||||
|
RecvChan <-chan Message
|
||||||
|
|
||||||
|
// Channel for this node to process delayed signals
|
||||||
|
TimeoutChan <-chan time.Time
|
||||||
|
|
||||||
|
Active atomic.Bool
|
||||||
|
|
||||||
|
writeSignalQueue bool
|
||||||
|
SignalQueue []QueuedSignal
|
||||||
|
NextSignal *QueuedSignal
|
||||||
|
}
|
||||||
|
|
||||||
|
func (node *Node) PostDeserialize(ctx *Context) error {
|
||||||
|
node.Extensions = map[ExtType]Extension{}
|
||||||
|
|
||||||
|
public := node.Key.Public().(ed25519.PublicKey)
|
||||||
|
node.ID = KeyID(public)
|
||||||
|
|
||||||
|
node.SendChan, node.RecvChan = NewMessageQueue(NODE_INITIAL_QUEUE_SIZE)
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (node *Node) QueueSignal(time time.Time, signal Signal) {
|
||||||
|
node.SignalQueue = append(node.SignalQueue, QueuedSignal{signal, time})
|
||||||
|
node.NextSignal, node.TimeoutChan = SoonestSignal(node.SignalQueue)
|
||||||
|
node.writeSignalQueue = true
|
||||||
|
}
|
||||||
|
|
||||||
|
func (node *Node) DequeueSignal(id uuid.UUID) error {
|
||||||
|
idx := -1
|
||||||
|
for i, q := range(node.SignalQueue) {
|
||||||
|
if q.Signal.ID() == id {
|
||||||
|
idx = i
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if idx == -1 {
|
||||||
|
return fmt.Errorf("%s is not in SignalQueue", id)
|
||||||
|
}
|
||||||
|
|
||||||
|
node.SignalQueue[idx] = node.SignalQueue[len(node.SignalQueue)-1]
|
||||||
|
node.SignalQueue = node.SignalQueue[:len(node.SignalQueue)-1]
|
||||||
|
node.NextSignal, node.TimeoutChan = SoonestSignal(node.SignalQueue)
|
||||||
|
node.writeSignalQueue = true
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func SoonestSignal(signals []QueuedSignal) (*QueuedSignal, <-chan time.Time) {
|
||||||
|
var soonest_signal *QueuedSignal
|
||||||
|
var soonest_time time.Time
|
||||||
|
for i, signal := range(signals) {
|
||||||
|
if signal.Time.Compare(soonest_time) == -1 || soonest_signal == nil {
|
||||||
|
soonest_signal = &signals[i]
|
||||||
|
soonest_time = signal.Time
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if soonest_signal != nil {
|
||||||
|
if time.Now().Compare(soonest_time) == -1 {
|
||||||
|
return soonest_signal, time.After(time.Until(soonest_signal.Time))
|
||||||
|
} else {
|
||||||
|
c := make(chan time.Time, 1)
|
||||||
|
c <- soonest_time
|
||||||
|
return soonest_signal, c
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
return nil, nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func runNode(ctx *Context, node *Node, status chan string, control chan string) {
|
||||||
|
ctx.Log.Logf("node", "RUN_START: %s", node.ID)
|
||||||
|
err := nodeLoop(ctx, node, status, control)
|
||||||
|
if err != nil {
|
||||||
|
ctx.Log.Logf("node", "%s runNode err %s", node.ID, err)
|
||||||
|
}
|
||||||
|
ctx.Log.Logf("node", "RUN_STOP: %s", node.ID)
|
||||||
|
}
|
||||||
|
|
||||||
|
type StringError string
|
||||||
|
func (err StringError) String() string {
|
||||||
|
return string(err)
|
||||||
|
}
|
||||||
|
func (err StringError) Error() string {
|
||||||
|
return err.String()
|
||||||
|
}
|
||||||
|
func (err StringError) MarshalBinary() ([]byte, error) {
|
||||||
|
return []byte(string(err)), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (node *Node) ReadFields(ctx *Context, fields []string)map[string]any {
|
||||||
|
ctx.Log.Logf("read_field", "Reading %+v on %+v", fields, node.ID)
|
||||||
|
values := map[string]any{}
|
||||||
|
|
||||||
|
node_info := ctx.NodeTypes[node.Type]
|
||||||
|
|
||||||
|
for _, field_name := range(fields) {
|
||||||
|
field_info, mapped := node_info.Fields[field_name]
|
||||||
|
if mapped {
|
||||||
|
ext := node.Extensions[field_info.Extension]
|
||||||
|
values[field_name] = reflect.ValueOf(ext).Elem().FieldByIndex(field_info.Index).Interface()
|
||||||
|
} else {
|
||||||
|
values[field_name] = fmt.Errorf("NodeType %s has no field %s", node.Type, field_name)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return values
|
||||||
|
}
|
||||||
|
|
||||||
|
// Main Loop for nodes
|
||||||
|
func nodeLoop(ctx *Context, node *Node, status chan string, control chan string) error {
|
||||||
|
is_started := node.Active.CompareAndSwap(false, true)
|
||||||
|
if is_started == false {
|
||||||
|
return fmt.Errorf("%s is already started, will not start again", node.ID)
|
||||||
|
} else {
|
||||||
|
ctx.Log.Logf("node", "Set %s active", node.ID)
|
||||||
|
}
|
||||||
|
|
||||||
|
ctx.Log.Logf("node_ext", "Loading extensions for %s", node.ID)
|
||||||
|
|
||||||
|
for _, extension := range(node.Extensions) {
|
||||||
|
ctx.Log.Logf("node_ext", "Loading extension %s for %s", reflect.TypeOf(extension), node.ID)
|
||||||
|
err := extension.Load(ctx, node)
|
||||||
|
if err != nil {
|
||||||
|
ctx.Log.Logf("node_ext", "Failed to load extension %s on node %s", reflect.TypeOf(extension), node.ID)
|
||||||
|
node.Active.Store(false)
|
||||||
|
return err
|
||||||
|
} else {
|
||||||
|
ctx.Log.Logf("node_ext", "Loaded extension %s on node %s", reflect.TypeOf(extension), node.ID)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
ctx.Log.Logf("node_ext", "Loaded extensions for %s", node.ID)
|
||||||
|
|
||||||
|
status <- "active"
|
||||||
|
|
||||||
|
running := true
|
||||||
|
for running {
|
||||||
|
var signal Signal
|
||||||
|
var source NodeID
|
||||||
|
|
||||||
|
select {
|
||||||
|
case command := <-control:
|
||||||
|
switch command {
|
||||||
|
case "stop":
|
||||||
|
running = false
|
||||||
|
case "pause":
|
||||||
|
status <- "paused"
|
||||||
|
command := <- control
|
||||||
|
switch command {
|
||||||
|
case "resume":
|
||||||
|
status <- "resumed"
|
||||||
|
case "stop":
|
||||||
|
running = false
|
||||||
|
}
|
||||||
|
default:
|
||||||
|
ctx.Log.Logf("node", "Unknown control command %s", command)
|
||||||
|
}
|
||||||
|
case <-node.TimeoutChan:
|
||||||
|
signal = node.NextSignal.Signal
|
||||||
|
source = node.ID
|
||||||
|
|
||||||
|
t := node.NextSignal.Time
|
||||||
|
i := -1
|
||||||
|
for j, queued := range(node.SignalQueue) {
|
||||||
|
if queued.Signal.ID() == node.NextSignal.Signal.ID() {
|
||||||
|
i = j
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if i == -1 {
|
||||||
|
ctx.Log.Logf("node", "node.NextSignal not in node.SignalQueue, paniccing")
|
||||||
|
panic("node.NextSignal not in node.SignalQueue")
|
||||||
|
}
|
||||||
|
l := len(node.SignalQueue)
|
||||||
|
node.SignalQueue[i] = node.SignalQueue[l-1]
|
||||||
|
node.SignalQueue = node.SignalQueue[:(l-1)]
|
||||||
|
|
||||||
|
node.NextSignal, node.TimeoutChan = SoonestSignal(node.SignalQueue)
|
||||||
|
node.writeSignalQueue = true
|
||||||
|
|
||||||
|
if node.NextSignal == nil {
|
||||||
|
ctx.Log.Logf("node", "NODE_TIMEOUT(%s) - PROCESSING %+v@%s - NEXT_SIGNAL nil@%+v", node.ID, signal, t, node.TimeoutChan)
|
||||||
|
} else {
|
||||||
|
ctx.Log.Logf("node", "NODE_TIMEOUT(%s) - PROCESSING %+v@%s - NEXT_SIGNAL: %s@%s", node.ID, signal, t, node.NextSignal, node.NextSignal.Time)
|
||||||
|
}
|
||||||
|
case msg := <- node.RecvChan:
|
||||||
|
signal = msg.Signal
|
||||||
|
source = msg.Node
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
switch sig := signal.(type) {
|
||||||
|
case *ReadSignal:
|
||||||
|
result := node.ReadFields(ctx, sig.Fields)
|
||||||
|
msgs := []Message{}
|
||||||
|
msgs = append(msgs, Message{source, NewReadResultSignal(sig.ID(), node.ID, node.Type, result)})
|
||||||
|
ctx.Send(node, msgs)
|
||||||
|
|
||||||
|
default:
|
||||||
|
err := node.Process(ctx, source, signal)
|
||||||
|
if err != nil {
|
||||||
|
ctx.Log.Logf("node", "%s process error %s", node.ID, err)
|
||||||
|
panic(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
stopped := node.Active.CompareAndSwap(true, false)
|
||||||
|
if stopped == false {
|
||||||
|
panic("BAD_STATE: stopping already stopped node")
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, extension := range(node.Extensions) {
|
||||||
|
extension.Unload(ctx, node)
|
||||||
|
}
|
||||||
|
|
||||||
|
status <- "stopped"
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (node *Node) QueueChanges(ctx *Context, changes map[ExtType]Changes) error {
|
||||||
|
node_info, exists := ctx.NodeTypes[node.Type]
|
||||||
|
if exists == false {
|
||||||
|
return fmt.Errorf("Node type not in context, can't map changes to field names")
|
||||||
|
} else {
|
||||||
|
fields := []string{}
|
||||||
|
for ext_type, ext_changes := range(changes) {
|
||||||
|
ext_map, ext_mapped := node_info.ReverseFields[ext_type]
|
||||||
|
if ext_mapped {
|
||||||
|
for _, ext_tag := range(ext_changes) {
|
||||||
|
field_name, tag_mapped := ext_map[ext_tag]
|
||||||
|
if tag_mapped {
|
||||||
|
fields = append(fields, field_name)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
ctx.Log.Logf("changes", "Changes to queue from %+v: %+v", node_info.ReverseFields, fields)
|
||||||
|
if len(fields) > 0 {
|
||||||
|
node.QueueSignal(time.Time{}, NewStatusSignal(node.ID, fields))
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (node *Node) Process(ctx *Context, source NodeID, signal Signal) error {
|
||||||
|
messages := []Message{}
|
||||||
|
changes := map[ExtType]Changes{}
|
||||||
|
for ext_type, ext := range(node.Extensions) {
|
||||||
|
ext_messages, ext_changes := ext.Process(ctx, node, source, signal)
|
||||||
|
if len(ext_messages) != 0 {
|
||||||
|
messages = append(messages, ext_messages...)
|
||||||
|
}
|
||||||
|
if len(ext_changes) != 0 {
|
||||||
|
changes[ext_type] = ext_changes
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(messages) != 0 {
|
||||||
|
send_err := ctx.Send(node, messages)
|
||||||
|
if send_err != nil {
|
||||||
|
return send_err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(changes) != 0 {
|
||||||
|
ctx.Log.Logf("changes", "Changes to %s from %+v: %+v", node.ID, signal, changes)
|
||||||
|
status_err := node.QueueChanges(ctx, changes)
|
||||||
|
if status_err != nil {
|
||||||
|
return status_err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func GetCtx[C any, E any, T interface { *E; Extension}](ctx *Context) (C, error) {
|
||||||
|
var zero_ctx C
|
||||||
|
ext_type := ExtType(SerializedTypeFor[E]())
|
||||||
|
ext_info, ok := ctx.Extensions[ext_type]
|
||||||
|
if ok == false {
|
||||||
|
return zero_ctx, fmt.Errorf("%+v is not an extension in ctx", ext_type)
|
||||||
|
}
|
||||||
|
|
||||||
|
ext_ctx, ok := ext_info.Data.(C)
|
||||||
|
if ok == false {
|
||||||
|
return zero_ctx, fmt.Errorf("context for %+v is %+v, not %+v", ext_type, reflect.TypeOf(ext_info.Data), reflect.TypeOf(zero_ctx))
|
||||||
|
}
|
||||||
|
|
||||||
|
return ext_ctx, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func GetExt[E any, T interface { *E; Extension}](node *Node) (T, error) {
|
||||||
|
var zero T
|
||||||
|
ext_type := ExtType(SerializedTypeFor[E]())
|
||||||
|
ext, exists := node.Extensions[ext_type]
|
||||||
|
if exists == false {
|
||||||
|
return zero, fmt.Errorf("%+v does not have %+v extension - %+v", node.ID, ext_type, node.Extensions)
|
||||||
|
}
|
||||||
|
|
||||||
|
ret, ok := ext.(T)
|
||||||
|
if ok == false {
|
||||||
|
return zero, fmt.Errorf("%+v in %+v is wrong type(%+v), expecting %+v", ext_type, node.ID, reflect.TypeOf(ext), reflect.TypeOf(zero))
|
||||||
|
}
|
||||||
|
|
||||||
|
return ret, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func KeyID(pub ed25519.PublicKey) NodeID {
|
||||||
|
id := uuid.NewHash(sha512.New(), ZeroUUID, pub, 3)
|
||||||
|
return NodeID(id)
|
||||||
|
}
|
@ -0,0 +1,55 @@
|
|||||||
|
package graphvent
|
||||||
|
|
||||||
|
import (
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
"crypto/rand"
|
||||||
|
"crypto/ed25519"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestNodeDB(t *testing.T) {
|
||||||
|
ctx := logTestContext(t, []string{"test", "node", "db"})
|
||||||
|
|
||||||
|
node_listener := NewListenerExt(10)
|
||||||
|
node, err := ctx.NewNode(nil, "Node", NewLockableExt(nil), node_listener)
|
||||||
|
fatalErr(t, err)
|
||||||
|
|
||||||
|
err = ctx.Stop()
|
||||||
|
fatalErr(t, err)
|
||||||
|
|
||||||
|
_, err = ctx.GetNode(node.ID)
|
||||||
|
fatalErr(t, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestNodeRead(t *testing.T) {
|
||||||
|
ctx := logTestContext(t, []string{"test"})
|
||||||
|
|
||||||
|
n1_pub, n1_key, err := ed25519.GenerateKey(rand.Reader)
|
||||||
|
fatalErr(t, err)
|
||||||
|
n2_pub, n2_key, err := ed25519.GenerateKey(rand.Reader)
|
||||||
|
fatalErr(t, err)
|
||||||
|
|
||||||
|
n1_id := KeyID(n1_pub)
|
||||||
|
n2_id := KeyID(n2_pub)
|
||||||
|
|
||||||
|
ctx.Log.Logf("test", "N1: %s", n1_id)
|
||||||
|
ctx.Log.Logf("test", "N2: %s", n2_id)
|
||||||
|
|
||||||
|
n2_listener := NewListenerExt(10)
|
||||||
|
n2, err := ctx.NewNode(n2_key, "Node", n2_listener)
|
||||||
|
fatalErr(t, err)
|
||||||
|
|
||||||
|
n1, err := ctx.NewNode(n1_key, "Node", NewListenerExt(10))
|
||||||
|
fatalErr(t, err)
|
||||||
|
|
||||||
|
read_sig := NewReadSignal([]string{"buffer"})
|
||||||
|
msgs := []Message{{n1.ID, read_sig}}
|
||||||
|
err = ctx.Send(n2, msgs)
|
||||||
|
fatalErr(t, err)
|
||||||
|
|
||||||
|
res, err := WaitForSignal(n2_listener.Chan, 10*time.Millisecond, func(sig *ReadResultSignal) bool {
|
||||||
|
return true
|
||||||
|
})
|
||||||
|
fatalErr(t, err)
|
||||||
|
ctx.Log.Logf("test", "READ_RESULT: %+v", res)
|
||||||
|
}
|
@ -0,0 +1,744 @@
|
|||||||
|
package graphvent
|
||||||
|
|
||||||
|
import (
|
||||||
|
"crypto/sha512"
|
||||||
|
"encoding/binary"
|
||||||
|
"fmt"
|
||||||
|
"reflect"
|
||||||
|
"math"
|
||||||
|
)
|
||||||
|
|
||||||
|
type SerializedType uint64
|
||||||
|
|
||||||
|
func (t SerializedType) String() string {
|
||||||
|
return fmt.Sprintf("0x%x", uint64(t))
|
||||||
|
}
|
||||||
|
|
||||||
|
type ExtType SerializedType
|
||||||
|
|
||||||
|
func (t ExtType) String() string {
|
||||||
|
return fmt.Sprintf("0x%x", uint64(t))
|
||||||
|
}
|
||||||
|
|
||||||
|
type NodeType SerializedType
|
||||||
|
|
||||||
|
func (t NodeType) String() string {
|
||||||
|
return fmt.Sprintf("0x%x", uint64(t))
|
||||||
|
}
|
||||||
|
|
||||||
|
type SignalType SerializedType
|
||||||
|
|
||||||
|
func (t SignalType) String() string {
|
||||||
|
return fmt.Sprintf("0x%x", uint64(t))
|
||||||
|
}
|
||||||
|
|
||||||
|
type FieldTag SerializedType
|
||||||
|
|
||||||
|
func (t FieldTag) String() string {
|
||||||
|
return fmt.Sprintf("0x%x", uint64(t))
|
||||||
|
}
|
||||||
|
|
||||||
|
func NodeTypeFor(name string) NodeType {
|
||||||
|
digest := []byte("GRAPHVENT_NODE - " + name)
|
||||||
|
|
||||||
|
hash := sha512.Sum512(digest)
|
||||||
|
return NodeType(binary.BigEndian.Uint64(hash[0:8]))
|
||||||
|
}
|
||||||
|
|
||||||
|
func SerializeType(t fmt.Stringer) SerializedType {
|
||||||
|
digest := []byte(t.String())
|
||||||
|
hash := sha512.Sum512(digest)
|
||||||
|
return SerializedType(binary.BigEndian.Uint64(hash[0:8]))
|
||||||
|
}
|
||||||
|
|
||||||
|
func SerializedTypeFor[T any]() SerializedType {
|
||||||
|
return SerializeType(reflect.TypeFor[T]())
|
||||||
|
}
|
||||||
|
|
||||||
|
func ExtTypeFor[E any, T interface { *E; Extension}]() ExtType {
|
||||||
|
return ExtType(SerializedTypeFor[E]())
|
||||||
|
}
|
||||||
|
|
||||||
|
func ExtTypeOf(t reflect.Type) ExtType {
|
||||||
|
return ExtType(SerializeType(t.Elem()))
|
||||||
|
}
|
||||||
|
|
||||||
|
func SignalTypeFor[S Signal]() SignalType {
|
||||||
|
return SignalType(SerializedTypeFor[S]())
|
||||||
|
}
|
||||||
|
|
||||||
|
func Hash(base, data string) SerializedType {
|
||||||
|
digest := []byte(base + ":" + data)
|
||||||
|
hash := sha512.Sum512(digest)
|
||||||
|
return SerializedType(binary.BigEndian.Uint64(hash[0:8]))
|
||||||
|
}
|
||||||
|
|
||||||
|
func GetFieldTag(tag string) FieldTag {
|
||||||
|
return FieldTag(Hash("GRAPHVENT_FIELD_TAG", tag))
|
||||||
|
}
|
||||||
|
|
||||||
|
func TypeStack(ctx *Context, t reflect.Type, data []byte) (int, error) {
|
||||||
|
info, registered := ctx.Types[t]
|
||||||
|
if registered {
|
||||||
|
binary.BigEndian.PutUint64(data, uint64(info.Serialized))
|
||||||
|
return 8, nil
|
||||||
|
} else {
|
||||||
|
switch t.Kind() {
|
||||||
|
case reflect.Map:
|
||||||
|
binary.BigEndian.PutUint64(data, uint64(SerializeType(reflect.Map)))
|
||||||
|
|
||||||
|
key_written, err := TypeStack(ctx, t.Key(), data[8:])
|
||||||
|
if err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
|
||||||
|
elem_written, err := TypeStack(ctx, t.Elem(), data[8 + key_written:])
|
||||||
|
if err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return 8 + key_written + elem_written, nil
|
||||||
|
|
||||||
|
case reflect.Pointer:
|
||||||
|
binary.BigEndian.PutUint64(data, uint64(SerializeType(reflect.Pointer)))
|
||||||
|
|
||||||
|
elem_written, err := TypeStack(ctx, t.Elem(), data[8:])
|
||||||
|
if err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return 8 + elem_written, nil
|
||||||
|
case reflect.Slice:
|
||||||
|
binary.BigEndian.PutUint64(data, uint64(SerializeType(reflect.Slice)))
|
||||||
|
|
||||||
|
elem_written, err := TypeStack(ctx, t.Elem(), data[8:])
|
||||||
|
if err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return 8 + elem_written, nil
|
||||||
|
case reflect.Array:
|
||||||
|
binary.BigEndian.PutUint64(data, uint64(SerializeType(reflect.Array)))
|
||||||
|
binary.BigEndian.PutUint64(data[8:], uint64(t.Len()))
|
||||||
|
|
||||||
|
elem_written, err := TypeStack(ctx, t.Elem(), data[16:])
|
||||||
|
if err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return 16 + elem_written, nil
|
||||||
|
|
||||||
|
default:
|
||||||
|
return 0, fmt.Errorf("Hit %s, which is not a registered type", t.String())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func UnwrapStack(ctx *Context, stack []byte) (reflect.Type, []byte, error) {
|
||||||
|
first_bytes, left := split(stack, 8)
|
||||||
|
first := SerializedType(binary.BigEndian.Uint64(first_bytes))
|
||||||
|
|
||||||
|
info, registered := ctx.TypesReverse[first]
|
||||||
|
if registered {
|
||||||
|
return info.Reflect, left, nil
|
||||||
|
} else {
|
||||||
|
switch first {
|
||||||
|
case SerializeType(reflect.Map):
|
||||||
|
key_type, after_key, err := UnwrapStack(ctx, left)
|
||||||
|
if err != nil {
|
||||||
|
return nil, nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
elem_type, after_elem, err := UnwrapStack(ctx, after_key)
|
||||||
|
if err != nil {
|
||||||
|
return nil, nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return reflect.MapOf(key_type, elem_type), after_elem, nil
|
||||||
|
case SerializeType(reflect.Pointer):
|
||||||
|
elem_type, rest, err := UnwrapStack(ctx, left)
|
||||||
|
if err != nil {
|
||||||
|
return nil, nil, err
|
||||||
|
}
|
||||||
|
return reflect.PointerTo(elem_type), rest, nil
|
||||||
|
case SerializeType(reflect.Slice):
|
||||||
|
elem_type, rest, err := UnwrapStack(ctx, left)
|
||||||
|
if err != nil {
|
||||||
|
return nil, nil, err
|
||||||
|
}
|
||||||
|
return reflect.SliceOf(elem_type), rest, nil
|
||||||
|
case SerializeType(reflect.Array):
|
||||||
|
length_bytes, left := split(left, 8)
|
||||||
|
length := int(binary.BigEndian.Uint64(length_bytes))
|
||||||
|
|
||||||
|
elem_type, rest, err := UnwrapStack(ctx, left)
|
||||||
|
if err != nil {
|
||||||
|
return nil, nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return reflect.ArrayOf(length, elem_type), rest, nil
|
||||||
|
default:
|
||||||
|
return nil, nil, fmt.Errorf("Type stack %+v not recognized", stack)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func Serialize[T any](ctx *Context, value T, data []byte) (int, error) {
|
||||||
|
return SerializeValue(ctx, reflect.ValueOf(&value).Elem(), data)
|
||||||
|
}
|
||||||
|
|
||||||
|
func Deserialize[T any](ctx *Context, data []byte) (T, error) {
|
||||||
|
reflect_type := reflect.TypeFor[T]()
|
||||||
|
var zero T
|
||||||
|
value, left, err := DeserializeValue(ctx, data, reflect_type)
|
||||||
|
if err != nil {
|
||||||
|
return zero, err
|
||||||
|
} else if len(left) != 0 {
|
||||||
|
return zero, fmt.Errorf("%d/%d bytes left after deserializing %+v", len(left), len(data), value)
|
||||||
|
} else if value.Type() != reflect_type {
|
||||||
|
return zero, fmt.Errorf("Deserialized type %s does not match %s", value.Type(), reflect_type)
|
||||||
|
}
|
||||||
|
|
||||||
|
return value.Interface().(T), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func SerializedSize(ctx *Context, value reflect.Value) (int, error) {
|
||||||
|
var sizefn SerializedSizeFn = nil
|
||||||
|
|
||||||
|
info, registered := ctx.Types[value.Type()]
|
||||||
|
if registered {
|
||||||
|
sizefn = info.SerializedSize
|
||||||
|
}
|
||||||
|
|
||||||
|
if sizefn == nil {
|
||||||
|
switch value.Type().Kind() {
|
||||||
|
case reflect.Bool:
|
||||||
|
return 1, nil
|
||||||
|
|
||||||
|
case reflect.Int8:
|
||||||
|
return 1, nil
|
||||||
|
case reflect.Int16:
|
||||||
|
return 2, nil
|
||||||
|
case reflect.Int32:
|
||||||
|
return 4, nil
|
||||||
|
case reflect.Int64:
|
||||||
|
fallthrough
|
||||||
|
case reflect.Int:
|
||||||
|
return 8, nil
|
||||||
|
|
||||||
|
case reflect.Uint8:
|
||||||
|
return 1, nil
|
||||||
|
case reflect.Uint16:
|
||||||
|
return 2, nil
|
||||||
|
case reflect.Uint32:
|
||||||
|
return 4, nil
|
||||||
|
case reflect.Uint64:
|
||||||
|
fallthrough
|
||||||
|
case reflect.Uint:
|
||||||
|
return 8, nil
|
||||||
|
|
||||||
|
case reflect.Float32:
|
||||||
|
return 4, nil
|
||||||
|
case reflect.Float64:
|
||||||
|
return 8, nil
|
||||||
|
|
||||||
|
case reflect.String:
|
||||||
|
return 8 + value.Len(), nil
|
||||||
|
|
||||||
|
case reflect.Pointer:
|
||||||
|
if value.IsNil() {
|
||||||
|
return 1, nil
|
||||||
|
} else {
|
||||||
|
elem_len, err := SerializedSize(ctx, value.Elem())
|
||||||
|
if err != nil {
|
||||||
|
return 0, err
|
||||||
|
} else {
|
||||||
|
return 1 + elem_len, nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
case reflect.Slice:
|
||||||
|
if value.IsNil() {
|
||||||
|
return 1, nil
|
||||||
|
} else {
|
||||||
|
elem_total := 0
|
||||||
|
for i := 0; i < value.Len(); i++ {
|
||||||
|
elem_len, err := SerializedSize(ctx, value.Index(i))
|
||||||
|
if err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
elem_total += elem_len
|
||||||
|
}
|
||||||
|
return 9 + elem_total, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
case reflect.Array:
|
||||||
|
total := 0
|
||||||
|
for i := 0; i < value.Len(); i++ {
|
||||||
|
elem_len, err := SerializedSize(ctx, value.Index(i))
|
||||||
|
if err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
total += elem_len
|
||||||
|
}
|
||||||
|
return total, nil
|
||||||
|
|
||||||
|
case reflect.Map:
|
||||||
|
if value.IsNil() {
|
||||||
|
return 1, nil
|
||||||
|
} else {
|
||||||
|
key := reflect.New(value.Type().Key()).Elem()
|
||||||
|
val := reflect.New(value.Type().Elem()).Elem()
|
||||||
|
iter := value.MapRange()
|
||||||
|
|
||||||
|
total := 0
|
||||||
|
for iter.Next() {
|
||||||
|
key.SetIterKey(iter)
|
||||||
|
k, err := SerializedSize(ctx, key)
|
||||||
|
if err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
|
||||||
|
total += k
|
||||||
|
|
||||||
|
val.SetIterValue(iter)
|
||||||
|
v, err := SerializedSize(ctx, val)
|
||||||
|
if err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
|
||||||
|
total += v
|
||||||
|
}
|
||||||
|
|
||||||
|
return 9 + total, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
case reflect.Struct:
|
||||||
|
if registered == false {
|
||||||
|
return 0, fmt.Errorf("Can't serialize unregistered struct %s", value.Type())
|
||||||
|
} else {
|
||||||
|
field_total := 0
|
||||||
|
for _, field_info := range(info.Fields) {
|
||||||
|
field_size, err := SerializedSize(ctx, value.FieldByIndex(field_info.Index))
|
||||||
|
if err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
|
||||||
|
field_total += 8
|
||||||
|
field_total += field_size
|
||||||
|
}
|
||||||
|
|
||||||
|
return 8 + field_total, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
case reflect.Interface:
|
||||||
|
// TODO get size of TypeStack instead of just using 128
|
||||||
|
elem_size, err := SerializedSize(ctx, value.Elem())
|
||||||
|
if err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return 128 + elem_size, nil
|
||||||
|
|
||||||
|
default:
|
||||||
|
return 0, fmt.Errorf("Don't know how to serialize %s", value.Type())
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
return sizefn(ctx, value)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func SerializeValue(ctx *Context, value reflect.Value, data []byte) (int, error) {
|
||||||
|
var serialize SerializeFn = nil
|
||||||
|
|
||||||
|
info, registered := ctx.Types[value.Type()]
|
||||||
|
if registered {
|
||||||
|
serialize = info.Serialize
|
||||||
|
}
|
||||||
|
|
||||||
|
if serialize == nil {
|
||||||
|
switch value.Type().Kind() {
|
||||||
|
case reflect.Bool:
|
||||||
|
if value.Bool() {
|
||||||
|
data[0] = 0xFF
|
||||||
|
} else {
|
||||||
|
data[0] = 0x00
|
||||||
|
}
|
||||||
|
return 1, nil
|
||||||
|
|
||||||
|
case reflect.Int8:
|
||||||
|
data[0] = byte(value.Int())
|
||||||
|
return 1, nil
|
||||||
|
case reflect.Int16:
|
||||||
|
binary.BigEndian.PutUint16(data, uint16(value.Int()))
|
||||||
|
return 2, nil
|
||||||
|
case reflect.Int32:
|
||||||
|
binary.BigEndian.PutUint32(data, uint32(value.Int()))
|
||||||
|
return 4, nil
|
||||||
|
case reflect.Int64:
|
||||||
|
fallthrough
|
||||||
|
case reflect.Int:
|
||||||
|
binary.BigEndian.PutUint64(data, uint64(value.Int()))
|
||||||
|
return 8, nil
|
||||||
|
|
||||||
|
case reflect.Uint8:
|
||||||
|
data[0] = byte(value.Uint())
|
||||||
|
return 1, nil
|
||||||
|
case reflect.Uint16:
|
||||||
|
binary.BigEndian.PutUint16(data, uint16(value.Uint()))
|
||||||
|
return 2, nil
|
||||||
|
case reflect.Uint32:
|
||||||
|
binary.BigEndian.PutUint32(data, uint32(value.Uint()))
|
||||||
|
return 4, nil
|
||||||
|
case reflect.Uint64:
|
||||||
|
fallthrough
|
||||||
|
case reflect.Uint:
|
||||||
|
binary.BigEndian.PutUint64(data, value.Uint())
|
||||||
|
return 8, nil
|
||||||
|
|
||||||
|
case reflect.Float32:
|
||||||
|
binary.BigEndian.PutUint32(data, math.Float32bits(float32(value.Float())))
|
||||||
|
return 4, nil
|
||||||
|
case reflect.Float64:
|
||||||
|
binary.BigEndian.PutUint64(data, math.Float64bits(value.Float()))
|
||||||
|
return 8, nil
|
||||||
|
|
||||||
|
case reflect.String:
|
||||||
|
binary.BigEndian.PutUint64(data, uint64(value.Len()))
|
||||||
|
copy(data[8:], []byte(value.String()))
|
||||||
|
return 8 + value.Len(), nil
|
||||||
|
|
||||||
|
case reflect.Pointer:
|
||||||
|
if value.IsNil() {
|
||||||
|
data[0] = 0x00
|
||||||
|
return 1, nil
|
||||||
|
} else {
|
||||||
|
data[0] = 0x01
|
||||||
|
written, err := SerializeValue(ctx, value.Elem(), data[1:])
|
||||||
|
if err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
return 1 + written, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
case reflect.Slice:
|
||||||
|
if value.IsNil() {
|
||||||
|
data[0] = 0x00
|
||||||
|
return 8, nil
|
||||||
|
} else {
|
||||||
|
data[0] = 0x01
|
||||||
|
binary.BigEndian.PutUint64(data[1:], uint64(value.Len()))
|
||||||
|
total_written := 0
|
||||||
|
for i := 0; i < value.Len(); i++ {
|
||||||
|
written, err := SerializeValue(ctx, value.Index(i), data[9+total_written:])
|
||||||
|
if err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
total_written += written
|
||||||
|
}
|
||||||
|
return 9 + total_written, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
case reflect.Array:
|
||||||
|
total_written := 0
|
||||||
|
for i := 0; i < value.Len(); i++ {
|
||||||
|
written, err := SerializeValue(ctx, value.Index(i), data[total_written:])
|
||||||
|
if err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
total_written += written
|
||||||
|
}
|
||||||
|
return total_written, nil
|
||||||
|
|
||||||
|
case reflect.Map:
|
||||||
|
if value.IsNil() {
|
||||||
|
data[0] = 0x00
|
||||||
|
return 1, nil
|
||||||
|
} else {
|
||||||
|
data[0] = 0x01
|
||||||
|
binary.BigEndian.PutUint64(data[1:], uint64(value.Len()))
|
||||||
|
|
||||||
|
key := reflect.New(value.Type().Key()).Elem()
|
||||||
|
val := reflect.New(value.Type().Elem()).Elem()
|
||||||
|
iter := value.MapRange()
|
||||||
|
total_written := 0
|
||||||
|
for iter.Next() {
|
||||||
|
key.SetIterKey(iter)
|
||||||
|
val.SetIterValue(iter)
|
||||||
|
|
||||||
|
k, err := SerializeValue(ctx, key, data[9+total_written:])
|
||||||
|
if err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
total_written += k
|
||||||
|
|
||||||
|
v, err := SerializeValue(ctx, val, data[9+total_written:])
|
||||||
|
if err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
total_written += v
|
||||||
|
}
|
||||||
|
return 9 + total_written, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
case reflect.Struct:
|
||||||
|
if registered == false {
|
||||||
|
return 0, fmt.Errorf("Cannot serialize unregistered struct %s", value.Type())
|
||||||
|
} else {
|
||||||
|
binary.BigEndian.PutUint64(data, uint64(len(info.Fields)))
|
||||||
|
|
||||||
|
total_written := 0
|
||||||
|
for field_tag, field_info := range(info.Fields) {
|
||||||
|
binary.BigEndian.PutUint64(data[8+total_written:], uint64(field_tag))
|
||||||
|
total_written += 8
|
||||||
|
written, err := SerializeValue(ctx, value.FieldByIndex(field_info.Index), data[8+total_written:])
|
||||||
|
if err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
total_written += written
|
||||||
|
}
|
||||||
|
return 8 + total_written, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
case reflect.Interface:
|
||||||
|
type_written, err := TypeStack(ctx, value.Elem().Type(), data)
|
||||||
|
|
||||||
|
elem_written, err := SerializeValue(ctx, value.Elem(), data[type_written:])
|
||||||
|
if err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return type_written + elem_written, nil
|
||||||
|
default:
|
||||||
|
return 0, fmt.Errorf("Don't know how to serialize %s", value.Type())
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
return serialize(ctx, value, data)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func split(data []byte, n int) ([]byte, []byte) {
|
||||||
|
return data[:n], data[n:]
|
||||||
|
}
|
||||||
|
|
||||||
|
func DeserializeValue(ctx *Context, data []byte, t reflect.Type) (reflect.Value, []byte, error) {
|
||||||
|
var deserialize DeserializeFn = nil
|
||||||
|
|
||||||
|
info, registered := ctx.Types[t]
|
||||||
|
if registered {
|
||||||
|
deserialize = info.Deserialize
|
||||||
|
}
|
||||||
|
|
||||||
|
if deserialize == nil {
|
||||||
|
switch t.Kind() {
|
||||||
|
case reflect.Bool:
|
||||||
|
used, left := split(data, 1)
|
||||||
|
value := reflect.New(t).Elem()
|
||||||
|
value.SetBool(used[0] != 0x00)
|
||||||
|
return value, left, nil
|
||||||
|
|
||||||
|
case reflect.Int8:
|
||||||
|
used, left := split(data, 1)
|
||||||
|
value := reflect.New(t).Elem()
|
||||||
|
value.SetInt(int64(used[0]))
|
||||||
|
return value, left, nil
|
||||||
|
case reflect.Int16:
|
||||||
|
used, left := split(data, 2)
|
||||||
|
value := reflect.New(t).Elem()
|
||||||
|
value.SetInt(int64(binary.BigEndian.Uint16(used)))
|
||||||
|
return value, left, nil
|
||||||
|
case reflect.Int32:
|
||||||
|
used, left := split(data, 4)
|
||||||
|
value := reflect.New(t).Elem()
|
||||||
|
value.SetInt(int64(binary.BigEndian.Uint32(used)))
|
||||||
|
return value, left, nil
|
||||||
|
case reflect.Int64:
|
||||||
|
fallthrough
|
||||||
|
case reflect.Int:
|
||||||
|
used, left := split(data, 8)
|
||||||
|
value := reflect.New(t).Elem()
|
||||||
|
value.SetInt(int64(binary.BigEndian.Uint64(used)))
|
||||||
|
return value, left, nil
|
||||||
|
|
||||||
|
case reflect.Uint8:
|
||||||
|
used, left := split(data, 1)
|
||||||
|
value := reflect.New(t).Elem()
|
||||||
|
value.SetUint(uint64(used[0]))
|
||||||
|
return value, left, nil
|
||||||
|
case reflect.Uint16:
|
||||||
|
used, left := split(data, 2)
|
||||||
|
value := reflect.New(t).Elem()
|
||||||
|
value.SetUint(uint64(binary.BigEndian.Uint16(used)))
|
||||||
|
return value, left, nil
|
||||||
|
case reflect.Uint32:
|
||||||
|
used, left := split(data, 4)
|
||||||
|
value := reflect.New(t).Elem()
|
||||||
|
value.SetUint(uint64(binary.BigEndian.Uint32(used)))
|
||||||
|
return value, left, nil
|
||||||
|
case reflect.Uint64:
|
||||||
|
fallthrough
|
||||||
|
case reflect.Uint:
|
||||||
|
used, left := split(data, 8)
|
||||||
|
value := reflect.New(t).Elem()
|
||||||
|
value.SetUint(binary.BigEndian.Uint64(used))
|
||||||
|
return value, left, nil
|
||||||
|
|
||||||
|
case reflect.Float32:
|
||||||
|
used, left := split(data, 4)
|
||||||
|
value := reflect.New(t).Elem()
|
||||||
|
value.SetFloat(float64(math.Float32frombits(binary.BigEndian.Uint32(used))))
|
||||||
|
return value, left, nil
|
||||||
|
case reflect.Float64:
|
||||||
|
used, left := split(data, 8)
|
||||||
|
value := reflect.New(t).Elem()
|
||||||
|
value.SetFloat(math.Float64frombits(binary.BigEndian.Uint64(used)))
|
||||||
|
return value, left, nil
|
||||||
|
|
||||||
|
case reflect.String:
|
||||||
|
length, after_len := split(data, 8)
|
||||||
|
used, left := split(after_len, int(binary.BigEndian.Uint64(length)))
|
||||||
|
value := reflect.New(t).Elem()
|
||||||
|
value.SetString(string(used))
|
||||||
|
return value, left, nil
|
||||||
|
|
||||||
|
case reflect.Pointer:
|
||||||
|
flags, after_flags := split(data, 1)
|
||||||
|
value := reflect.New(t).Elem()
|
||||||
|
if flags[0] == 0x00 {
|
||||||
|
value.SetZero()
|
||||||
|
return value, after_flags, nil
|
||||||
|
} else {
|
||||||
|
elem_value, after_elem, err := DeserializeValue(ctx, after_flags, t.Elem())
|
||||||
|
if err != nil {
|
||||||
|
return reflect.Value{}, nil, err
|
||||||
|
}
|
||||||
|
value.Set(elem_value.Addr())
|
||||||
|
return value, after_elem, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
case reflect.Slice:
|
||||||
|
nil_byte := data[0]
|
||||||
|
data = data[1:]
|
||||||
|
if nil_byte == 0x00 {
|
||||||
|
return reflect.New(t).Elem(), data, nil
|
||||||
|
} else {
|
||||||
|
len_bytes, left := split(data, 8)
|
||||||
|
length := int(binary.BigEndian.Uint64(len_bytes))
|
||||||
|
value := reflect.MakeSlice(t, length, length)
|
||||||
|
for i := 0; i < length; i++ {
|
||||||
|
var elem_value reflect.Value
|
||||||
|
var err error
|
||||||
|
elem_value, left, err = DeserializeValue(ctx, left, t.Elem())
|
||||||
|
if err != nil {
|
||||||
|
return reflect.Value{}, nil, err
|
||||||
|
}
|
||||||
|
value.Index(i).Set(elem_value)
|
||||||
|
}
|
||||||
|
return value, left, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
case reflect.Array:
|
||||||
|
value := reflect.New(t).Elem()
|
||||||
|
left := data
|
||||||
|
for i := 0; i < t.Len(); i++ {
|
||||||
|
var elem_value reflect.Value
|
||||||
|
var err error
|
||||||
|
elem_value, left, err = DeserializeValue(ctx, left, t.Elem())
|
||||||
|
if err != nil {
|
||||||
|
return reflect.Value{}, nil, err
|
||||||
|
}
|
||||||
|
value.Index(i).Set(elem_value)
|
||||||
|
}
|
||||||
|
return value, left, nil
|
||||||
|
|
||||||
|
case reflect.Map:
|
||||||
|
flags, after_flags := split(data, 1)
|
||||||
|
if flags[0] == 0x00 {
|
||||||
|
return reflect.New(t).Elem(), after_flags, nil
|
||||||
|
} else {
|
||||||
|
len_bytes, left := split(after_flags, 8)
|
||||||
|
length := int(binary.BigEndian.Uint64(len_bytes))
|
||||||
|
|
||||||
|
value := reflect.MakeMapWithSize(t, length)
|
||||||
|
|
||||||
|
for i := 0; i < length; i++ {
|
||||||
|
var key_value reflect.Value
|
||||||
|
var val_value reflect.Value
|
||||||
|
var err error
|
||||||
|
|
||||||
|
key_value, left, err = DeserializeValue(ctx, left, t.Key())
|
||||||
|
if err != nil {
|
||||||
|
return reflect.Value{}, nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
val_value, left, err = DeserializeValue(ctx, left, t.Elem())
|
||||||
|
if err != nil {
|
||||||
|
return reflect.Value{}, nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
value.SetMapIndex(key_value, val_value)
|
||||||
|
}
|
||||||
|
|
||||||
|
return value, left, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
case reflect.Struct:
|
||||||
|
info, mapped := ctx.Types[t]
|
||||||
|
if mapped {
|
||||||
|
value := reflect.New(t).Elem()
|
||||||
|
|
||||||
|
num_field_bytes, left := split(data, 8)
|
||||||
|
num_fields := int(binary.BigEndian.Uint64(num_field_bytes))
|
||||||
|
|
||||||
|
for i := 0; i < num_fields; i++ {
|
||||||
|
var tag_bytes []byte
|
||||||
|
|
||||||
|
tag_bytes, left = split(left, 8)
|
||||||
|
field_tag := FieldTag(binary.BigEndian.Uint64(tag_bytes))
|
||||||
|
|
||||||
|
field_info, mapped := info.Fields[field_tag]
|
||||||
|
if mapped {
|
||||||
|
var field_val reflect.Value
|
||||||
|
var err error
|
||||||
|
field_val, left, err = DeserializeValue(ctx, left, field_info.Type)
|
||||||
|
if err != nil {
|
||||||
|
return reflect.Value{}, nil, err
|
||||||
|
}
|
||||||
|
value.FieldByIndex(field_info.Index).Set(field_val)
|
||||||
|
} else {
|
||||||
|
return reflect.Value{}, nil, fmt.Errorf("Unknown field %s on struct %s", field_tag, t)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if info.PostDeserializeIndex != -1 {
|
||||||
|
post_deserialize_method := value.Addr().Method(info.PostDeserializeIndex)
|
||||||
|
post_deserialize_method.Call([]reflect.Value{reflect.ValueOf(ctx)})
|
||||||
|
}
|
||||||
|
return value, left, nil
|
||||||
|
} else {
|
||||||
|
return reflect.Value{}, nil, fmt.Errorf("Cannot deserialize unregistered struct %s", t)
|
||||||
|
}
|
||||||
|
|
||||||
|
case reflect.Interface:
|
||||||
|
elem_type, rest, err := UnwrapStack(ctx, data)
|
||||||
|
if err != nil {
|
||||||
|
return reflect.Value{}, nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
elem_val, left, err := DeserializeValue(ctx, rest, elem_type)
|
||||||
|
if err != nil {
|
||||||
|
return reflect.Value{}, nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
val := reflect.New(t).Elem()
|
||||||
|
val.Set(elem_val)
|
||||||
|
|
||||||
|
return val, left, nil
|
||||||
|
|
||||||
|
default:
|
||||||
|
return reflect.Value{}, nil, fmt.Errorf("Don't know how to deserialize %s", t)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
return deserialize(ctx, data)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,176 @@
|
|||||||
|
package graphvent
|
||||||
|
|
||||||
|
import (
|
||||||
|
"testing"
|
||||||
|
"reflect"
|
||||||
|
"github.com/google/uuid"
|
||||||
|
)
|
||||||
|
|
||||||
|
func testTypeStack[T any](t *testing.T, ctx *Context) {
|
||||||
|
buffer := [1024]byte{}
|
||||||
|
reflect_type := reflect.TypeFor[T]()
|
||||||
|
written, err := TypeStack(ctx, reflect_type, buffer[:])
|
||||||
|
fatalErr(t, err)
|
||||||
|
|
||||||
|
stack := buffer[:written]
|
||||||
|
|
||||||
|
ctx.Log.Logf("test", "TypeStack[%s]: %+v", reflect_type, stack)
|
||||||
|
|
||||||
|
unwrapped_type, rest, err := UnwrapStack(ctx, stack)
|
||||||
|
fatalErr(t, err)
|
||||||
|
|
||||||
|
if len(rest) != 0 {
|
||||||
|
t.Errorf("Types remaining after unwrapping %s: %+v", unwrapped_type, stack)
|
||||||
|
}
|
||||||
|
|
||||||
|
if unwrapped_type != reflect_type {
|
||||||
|
t.Errorf("Unwrapped type[%+v] doesn't match original[%+v]", unwrapped_type, reflect_type)
|
||||||
|
}
|
||||||
|
|
||||||
|
ctx.Log.Logf("test", "Unwrapped type[%s]: %s", reflect_type, reflect_type)
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSerializeTypes(t *testing.T) {
|
||||||
|
ctx := logTestContext(t, []string{"test"})
|
||||||
|
|
||||||
|
testTypeStack[int](t, ctx)
|
||||||
|
testTypeStack[map[int]string](t, ctx)
|
||||||
|
testTypeStack[string](t, ctx)
|
||||||
|
testTypeStack[*string](t, ctx)
|
||||||
|
testTypeStack[*map[string]*map[*string]int](t, ctx)
|
||||||
|
testTypeStack[[5]int](t, ctx)
|
||||||
|
testTypeStack[uuid.UUID](t, ctx)
|
||||||
|
testTypeStack[NodeID](t, ctx)
|
||||||
|
}
|
||||||
|
|
||||||
|
func testSerializeCompare[T comparable](t *testing.T, ctx *Context, value T) {
|
||||||
|
buffer := [1024]byte{}
|
||||||
|
written, err := Serialize(ctx, value, buffer[:])
|
||||||
|
fatalErr(t, err)
|
||||||
|
|
||||||
|
serialized := buffer[:written]
|
||||||
|
|
||||||
|
ctx.Log.Logf("test", "Serialized Value[%s : %+v]: %+v", reflect.TypeFor[T](), value, serialized)
|
||||||
|
|
||||||
|
deserialized, err := Deserialize[T](ctx, serialized)
|
||||||
|
fatalErr(t, err)
|
||||||
|
|
||||||
|
if value != deserialized {
|
||||||
|
t.Fatalf("Deserialized value[%+v] doesn't match original[%+v]", value, deserialized)
|
||||||
|
}
|
||||||
|
|
||||||
|
ctx.Log.Logf("test", "Deserialized Value[%+v]: %+v", value, deserialized)
|
||||||
|
}
|
||||||
|
|
||||||
|
func testSerializeList[L []T, T comparable](t *testing.T, ctx *Context, value L) {
|
||||||
|
buffer := [1024]byte{}
|
||||||
|
written, err := Serialize(ctx, value, buffer[:])
|
||||||
|
fatalErr(t, err)
|
||||||
|
|
||||||
|
serialized := buffer[:written]
|
||||||
|
|
||||||
|
ctx.Log.Logf("test", "Serialized Value[%s : %+v]: %+v", reflect.TypeFor[L](), value, serialized)
|
||||||
|
|
||||||
|
deserialized, err := Deserialize[L](ctx, serialized)
|
||||||
|
fatalErr(t, err)
|
||||||
|
|
||||||
|
for i, item := range(value) {
|
||||||
|
if item != deserialized[i] {
|
||||||
|
t.Fatalf("Deserialized list %+v does not match original %+v", value, deserialized)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
ctx.Log.Logf("test", "Deserialized Value[%+v]: %+v", value, deserialized)
|
||||||
|
}
|
||||||
|
|
||||||
|
func testSerializePointer[P interface {*T}, T comparable](t *testing.T, ctx *Context, value P) {
|
||||||
|
buffer := [1024]byte{}
|
||||||
|
|
||||||
|
written, err := Serialize(ctx, value, buffer[:])
|
||||||
|
fatalErr(t, err)
|
||||||
|
|
||||||
|
serialized := buffer[:written]
|
||||||
|
|
||||||
|
ctx.Log.Logf("test", "Serialized Value[%s : %+v]: %+v", reflect.TypeFor[P](), value, serialized)
|
||||||
|
|
||||||
|
deserialized, err := Deserialize[P](ctx, serialized)
|
||||||
|
fatalErr(t, err)
|
||||||
|
|
||||||
|
if value == nil && deserialized == nil {
|
||||||
|
ctx.Log.Logf("test", "Deserialized nil")
|
||||||
|
} else if value == nil {
|
||||||
|
t.Fatalf("Non-nil value[%+v] returned for nil value", deserialized)
|
||||||
|
} else if deserialized == nil {
|
||||||
|
t.Fatalf("Nil value returned for non-nil value[%+v]", value)
|
||||||
|
} else if *deserialized != *value {
|
||||||
|
t.Fatalf("Deserialized value[%+v] doesn't match original[%+v]", value, deserialized)
|
||||||
|
} else {
|
||||||
|
ctx.Log.Logf("test", "Deserialized Value[%+v]: %+v", *value, *deserialized)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func testSerialize[T any](t *testing.T, ctx *Context, value T) {
|
||||||
|
buffer := [1024]byte{}
|
||||||
|
written, err := Serialize(ctx, value, buffer[:])
|
||||||
|
fatalErr(t, err)
|
||||||
|
|
||||||
|
serialized := buffer[:written]
|
||||||
|
|
||||||
|
ctx.Log.Logf("test", "Serialized Value[%s : %+v]: %+v", reflect.TypeFor[T](), value, serialized)
|
||||||
|
|
||||||
|
deserialized, err := Deserialize[T](ctx, serialized)
|
||||||
|
fatalErr(t, err)
|
||||||
|
|
||||||
|
ctx.Log.Logf("test", "Deserialized Value[%+v]: %+v", value, deserialized)
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSerializeValues(t *testing.T) {
|
||||||
|
ctx := logTestContext(t, []string{"test"})
|
||||||
|
|
||||||
|
testSerialize(t, ctx, Extension(NewLockableExt(nil)))
|
||||||
|
|
||||||
|
testSerializeCompare[int8](t, ctx, -64)
|
||||||
|
testSerializeCompare[int16](t, ctx, -64)
|
||||||
|
testSerializeCompare[int32](t, ctx, -64)
|
||||||
|
testSerializeCompare[int64](t, ctx, -64)
|
||||||
|
testSerializeCompare[int](t, ctx, -64)
|
||||||
|
|
||||||
|
testSerializeCompare[uint8](t, ctx, 64)
|
||||||
|
testSerializeCompare[uint16](t, ctx, 64)
|
||||||
|
testSerializeCompare[uint32](t, ctx, 64)
|
||||||
|
testSerializeCompare[uint64](t, ctx, 64)
|
||||||
|
testSerializeCompare[uint](t, ctx, 64)
|
||||||
|
|
||||||
|
testSerializeCompare[string](t, ctx, "test")
|
||||||
|
|
||||||
|
a := 12
|
||||||
|
testSerializePointer[*int](t, ctx, &a)
|
||||||
|
|
||||||
|
b := "test"
|
||||||
|
testSerializePointer[*string](t, ctx, nil)
|
||||||
|
testSerializePointer[*string](t, ctx, &b)
|
||||||
|
|
||||||
|
testSerializeList(t, ctx, []int{1, 2, 3, 4, 5})
|
||||||
|
|
||||||
|
testSerializeCompare[bool](t, ctx, true)
|
||||||
|
testSerializeCompare[bool](t, ctx, false)
|
||||||
|
testSerializeCompare[int](t, ctx, -1)
|
||||||
|
testSerializeCompare[uint](t, ctx, 1)
|
||||||
|
testSerializeCompare[NodeID](t, ctx, RandID())
|
||||||
|
testSerializeCompare[*int](t, ctx, nil)
|
||||||
|
testSerializeCompare(t, ctx, "string")
|
||||||
|
|
||||||
|
testSerialize(t, ctx, map[string]string{
|
||||||
|
"Test": "Test",
|
||||||
|
"key": "String",
|
||||||
|
"": "",
|
||||||
|
})
|
||||||
|
|
||||||
|
testSerialize[map[string]string](t, ctx, nil)
|
||||||
|
|
||||||
|
testSerialize(t, ctx, NewListenerExt(10))
|
||||||
|
|
||||||
|
node, err := ctx.NewNode(nil, "Node")
|
||||||
|
fatalErr(t, err)
|
||||||
|
testSerialize(t, ctx, node)
|
||||||
|
}
|
@ -0,0 +1,261 @@
|
|||||||
|
package graphvent
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/google/uuid"
|
||||||
|
)
|
||||||
|
|
||||||
|
type TimeoutSignal struct {
|
||||||
|
ResponseHeader
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewTimeoutSignal(req_id uuid.UUID) *TimeoutSignal {
|
||||||
|
return &TimeoutSignal{
|
||||||
|
NewResponseHeader(req_id),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (signal TimeoutSignal) String() string {
|
||||||
|
return fmt.Sprintf("TimeoutSignal(%s)", &signal.ResponseHeader)
|
||||||
|
}
|
||||||
|
|
||||||
|
type SignalHeader struct {
|
||||||
|
Id uuid.UUID `gv:"id"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (signal SignalHeader) ID() uuid.UUID {
|
||||||
|
return signal.Id
|
||||||
|
}
|
||||||
|
|
||||||
|
func (header SignalHeader) String() string {
|
||||||
|
return fmt.Sprintf("%s", header.Id)
|
||||||
|
}
|
||||||
|
|
||||||
|
type ResponseSignal interface {
|
||||||
|
Signal
|
||||||
|
ResponseID() uuid.UUID
|
||||||
|
}
|
||||||
|
|
||||||
|
type ResponseHeader struct {
|
||||||
|
SignalHeader
|
||||||
|
ReqID uuid.UUID `gv:"req_id"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (header ResponseHeader) ResponseID() uuid.UUID {
|
||||||
|
return header.ReqID
|
||||||
|
}
|
||||||
|
|
||||||
|
func (header ResponseHeader) String() string {
|
||||||
|
return fmt.Sprintf("%s for %s", header.Id, header.ReqID)
|
||||||
|
}
|
||||||
|
|
||||||
|
type Signal interface {
|
||||||
|
fmt.Stringer
|
||||||
|
ID() uuid.UUID
|
||||||
|
}
|
||||||
|
|
||||||
|
func WaitForResponse(listener chan Signal, timeout time.Duration, req_id uuid.UUID) (ResponseSignal, []Signal, error) {
|
||||||
|
signals := []Signal{}
|
||||||
|
var timeout_channel <- chan time.Time
|
||||||
|
if timeout > 0 {
|
||||||
|
timeout_channel = time.After(timeout)
|
||||||
|
}
|
||||||
|
|
||||||
|
for true {
|
||||||
|
select {
|
||||||
|
case signal := <- listener:
|
||||||
|
if signal == nil {
|
||||||
|
return nil, signals, fmt.Errorf("LISTENER_CLOSED")
|
||||||
|
}
|
||||||
|
|
||||||
|
resp_signal, ok := signal.(ResponseSignal)
|
||||||
|
if ok == true && resp_signal.ResponseID() == req_id {
|
||||||
|
return resp_signal, signals, nil
|
||||||
|
} else {
|
||||||
|
signals = append(signals, signal)
|
||||||
|
}
|
||||||
|
|
||||||
|
case <-timeout_channel:
|
||||||
|
return nil, signals, fmt.Errorf("LISTENER_TIMEOUT")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil, signals, fmt.Errorf("UNREACHABLE")
|
||||||
|
}
|
||||||
|
|
||||||
|
//TODO: Add []Signal return as well for other signals
|
||||||
|
func WaitForSignal[S Signal](listener chan Signal, timeout time.Duration, check func(S)bool) (S, error) {
|
||||||
|
var zero S
|
||||||
|
var timeout_channel <- chan time.Time
|
||||||
|
if timeout > 0 {
|
||||||
|
timeout_channel = time.After(timeout)
|
||||||
|
}
|
||||||
|
for true {
|
||||||
|
select {
|
||||||
|
case signal := <- listener:
|
||||||
|
if signal == nil {
|
||||||
|
return zero, fmt.Errorf("LISTENER_CLOSED")
|
||||||
|
}
|
||||||
|
sig, ok := signal.(S)
|
||||||
|
if ok == true {
|
||||||
|
if check(sig) == true {
|
||||||
|
return sig, nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
case <-timeout_channel:
|
||||||
|
return zero, fmt.Errorf("LISTENER_TIMEOUT")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return zero, fmt.Errorf("LOOP_ENDED")
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewSignalHeader() SignalHeader {
|
||||||
|
return SignalHeader{
|
||||||
|
uuid.New(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewResponseHeader(req_id uuid.UUID) ResponseHeader {
|
||||||
|
return ResponseHeader{
|
||||||
|
NewSignalHeader(),
|
||||||
|
req_id,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type SuccessSignal struct {
|
||||||
|
ResponseHeader
|
||||||
|
}
|
||||||
|
|
||||||
|
func (signal SuccessSignal) String() string {
|
||||||
|
return fmt.Sprintf("SuccessSignal(%s)", signal.ResponseHeader)
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewSuccessSignal(req_id uuid.UUID) *SuccessSignal {
|
||||||
|
return &SuccessSignal{
|
||||||
|
NewResponseHeader(req_id),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type ErrorSignal struct {
|
||||||
|
ResponseHeader
|
||||||
|
Error string
|
||||||
|
}
|
||||||
|
func (signal ErrorSignal) String() string {
|
||||||
|
return fmt.Sprintf("ErrorSignal(%s, %s)", signal.ResponseHeader, signal.Error)
|
||||||
|
}
|
||||||
|
func NewErrorSignal(req_id uuid.UUID, fmt_string string, args ...interface{}) *ErrorSignal {
|
||||||
|
return &ErrorSignal{
|
||||||
|
NewResponseHeader(req_id),
|
||||||
|
fmt.Sprintf(fmt_string, args...),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type ACLTimeoutSignal struct {
|
||||||
|
ResponseHeader
|
||||||
|
}
|
||||||
|
func NewACLTimeoutSignal(req_id uuid.UUID) *ACLTimeoutSignal {
|
||||||
|
sig := &ACLTimeoutSignal{
|
||||||
|
NewResponseHeader(req_id),
|
||||||
|
}
|
||||||
|
return sig
|
||||||
|
}
|
||||||
|
|
||||||
|
type StatusSignal struct {
|
||||||
|
SignalHeader
|
||||||
|
Source NodeID `gv:"source"`
|
||||||
|
Fields []string `gv:"fields"`
|
||||||
|
}
|
||||||
|
func (signal StatusSignal) String() string {
|
||||||
|
return fmt.Sprintf("StatusSignal(%s: %+v)", signal.Source, signal.Fields)
|
||||||
|
}
|
||||||
|
func NewStatusSignal(source NodeID, fields []string) *StatusSignal {
|
||||||
|
return &StatusSignal{
|
||||||
|
NewSignalHeader(),
|
||||||
|
source,
|
||||||
|
fields,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type LinkSignal struct {
|
||||||
|
SignalHeader
|
||||||
|
NodeID NodeID
|
||||||
|
Action string
|
||||||
|
}
|
||||||
|
|
||||||
|
const (
|
||||||
|
LinkActionBase = "LINK_ACTION"
|
||||||
|
LinkActionAdd = "ADD"
|
||||||
|
)
|
||||||
|
|
||||||
|
func NewLinkSignal(action string, id NodeID) Signal {
|
||||||
|
return &LinkSignal{
|
||||||
|
NewSignalHeader(),
|
||||||
|
id,
|
||||||
|
action,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type LockSignal struct {
|
||||||
|
SignalHeader
|
||||||
|
}
|
||||||
|
func (signal LockSignal) String() string {
|
||||||
|
return fmt.Sprintf("LockSignal(%s)", signal.SignalHeader)
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewLockSignal() *LockSignal {
|
||||||
|
return &LockSignal{
|
||||||
|
NewSignalHeader(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type UnlockSignal struct {
|
||||||
|
SignalHeader
|
||||||
|
}
|
||||||
|
func (signal UnlockSignal) String() string {
|
||||||
|
return fmt.Sprintf("UnlockSignal(%s)", signal.SignalHeader)
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewUnlockSignal() *UnlockSignal {
|
||||||
|
return &UnlockSignal{
|
||||||
|
NewSignalHeader(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
type ReadSignal struct {
|
||||||
|
SignalHeader
|
||||||
|
Fields []string `json:"extensions"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (signal ReadSignal) String() string {
|
||||||
|
return fmt.Sprintf("ReadSignal(%s, %+v)", signal.SignalHeader, signal.Fields)
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewReadSignal(fields []string) *ReadSignal {
|
||||||
|
return &ReadSignal{
|
||||||
|
NewSignalHeader(),
|
||||||
|
fields,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type ReadResultSignal struct {
|
||||||
|
ResponseHeader
|
||||||
|
NodeID NodeID
|
||||||
|
NodeType NodeType
|
||||||
|
Fields map[string]any
|
||||||
|
}
|
||||||
|
|
||||||
|
func (signal ReadResultSignal) String() string {
|
||||||
|
return fmt.Sprintf("ReadResultSignal(%s, %s, %+v)", signal.ResponseHeader, signal.NodeID, signal.Fields)
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewReadResultSignal(req_id uuid.UUID, node_id NodeID, node_type NodeType, fields map[string]any) *ReadResultSignal {
|
||||||
|
return &ReadResultSignal{
|
||||||
|
NewResponseHeader(req_id),
|
||||||
|
node_id,
|
||||||
|
node_type,
|
||||||
|
fields,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -1,413 +0,0 @@
|
|||||||
package graphvent
|
|
||||||
|
|
||||||
import (
|
|
||||||
"fmt"
|
|
||||||
"time"
|
|
||||||
"errors"
|
|
||||||
"reflect"
|
|
||||||
"encoding/json"
|
|
||||||
)
|
|
||||||
|
|
||||||
// Update the threads listeners, and notify the parent to do the same
|
|
||||||
func (thread * BaseThread) PropagateUpdate(ctx * GraphContext, signal GraphSignal) {
|
|
||||||
UseStates(ctx, []GraphNode{thread}, func(states []NodeState) (interface{}, error) {
|
|
||||||
thread_state := states[0].(ThreadState)
|
|
||||||
if signal.Direction() == Up {
|
|
||||||
// Child->Parent, thread updates parent and connected requirement
|
|
||||||
if thread_state.Parent() != nil {
|
|
||||||
SendUpdate(ctx, thread_state.Parent(), signal)
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, dep := range(thread_state.Dependencies()) {
|
|
||||||
SendUpdate(ctx, dep, signal)
|
|
||||||
}
|
|
||||||
} else if signal.Direction() == Down {
|
|
||||||
// Parent->Child, updates children and dependencies
|
|
||||||
for _, child := range(thread_state.Children()) {
|
|
||||||
SendUpdate(ctx, child, signal)
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, requirement := range(thread_state.Requirements()) {
|
|
||||||
SendUpdate(ctx, requirement, signal)
|
|
||||||
}
|
|
||||||
} else if signal.Direction() == Direct {
|
|
||||||
|
|
||||||
} else {
|
|
||||||
panic(fmt.Sprintf("Invalid signal direction: %d", signal.Direction()))
|
|
||||||
}
|
|
||||||
|
|
||||||
return nil, nil
|
|
||||||
})
|
|
||||||
thread.signal <- signal
|
|
||||||
}
|
|
||||||
|
|
||||||
type ThreadInfo interface {
|
|
||||||
}
|
|
||||||
|
|
||||||
// An Thread is a lockable that has an additional parent->child relationship with other Threads
|
|
||||||
// This relationship allows the thread tree to be modified independent of the lockable state
|
|
||||||
type ThreadState interface {
|
|
||||||
LockHolderState
|
|
||||||
LockableState
|
|
||||||
|
|
||||||
Parent() Thread
|
|
||||||
SetParent(parent Thread)
|
|
||||||
Children() []Thread
|
|
||||||
ChildInfo(child NodeID) ThreadInfo
|
|
||||||
AddChild(child Thread, info ThreadInfo) error
|
|
||||||
}
|
|
||||||
|
|
||||||
type BaseThreadState struct {
|
|
||||||
BaseLockableState
|
|
||||||
parent Thread
|
|
||||||
children []Thread
|
|
||||||
child_info map[NodeID] ThreadInfo
|
|
||||||
info_type reflect.Type
|
|
||||||
}
|
|
||||||
|
|
||||||
type BaseThreadStateJSON struct {
|
|
||||||
Parent *NodeID `json:"parent"`
|
|
||||||
Children map[NodeID]interface{} `json:"children"`
|
|
||||||
LockableState *BaseLockableState `json:"lockable_state"`
|
|
||||||
}
|
|
||||||
|
|
||||||
func (state * BaseThreadState) MarshalJSON() ([]byte, error) {
|
|
||||||
children := map[NodeID]interface{}{}
|
|
||||||
for _, child := range(state.children) {
|
|
||||||
children[child.ID()] = state.child_info[child.ID()]
|
|
||||||
}
|
|
||||||
|
|
||||||
var parent_id *NodeID = nil
|
|
||||||
if state.parent != nil {
|
|
||||||
new_str := state.parent.ID()
|
|
||||||
parent_id = &new_str
|
|
||||||
}
|
|
||||||
|
|
||||||
return json.Marshal(&BaseThreadStateJSON{
|
|
||||||
Parent: parent_id,
|
|
||||||
Children: children,
|
|
||||||
LockableState: &state.BaseLockableState,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
func (state * BaseThreadState) Parent() Thread {
|
|
||||||
return state.parent
|
|
||||||
}
|
|
||||||
|
|
||||||
func (state * BaseThreadState) SetParent(parent Thread) {
|
|
||||||
state.parent = parent
|
|
||||||
}
|
|
||||||
|
|
||||||
func (state * BaseThreadState) Children() []Thread {
|
|
||||||
return state.children
|
|
||||||
}
|
|
||||||
|
|
||||||
func (state * BaseThreadState) ChildInfo(child NodeID) ThreadInfo {
|
|
||||||
return state.child_info[child]
|
|
||||||
}
|
|
||||||
|
|
||||||
func (state * BaseThreadState) AddChild(child Thread, info ThreadInfo) error {
|
|
||||||
if child == nil {
|
|
||||||
return fmt.Errorf("Will not connect nil to the thread tree")
|
|
||||||
}
|
|
||||||
|
|
||||||
_, exists := state.child_info[child.ID()]
|
|
||||||
if exists == true {
|
|
||||||
return fmt.Errorf("Will not connect the same child twice")
|
|
||||||
}
|
|
||||||
|
|
||||||
if info == nil && state.info_type != nil {
|
|
||||||
return fmt.Errorf("nil info passed when expecting info")
|
|
||||||
} else if info != nil {
|
|
||||||
if reflect.TypeOf(info) != state.info_type {
|
|
||||||
return fmt.Errorf("info type mismatch, expecting %+v", state.info_type)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
state.children = append(state.children, child)
|
|
||||||
state.child_info[child.ID()] = info
|
|
||||||
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func checkIfChild(ctx * GraphContext, thread_id NodeID, cur_state ThreadState, cur_id NodeID) bool {
|
|
||||||
for _, child := range(cur_state.Children()) {
|
|
||||||
if child.ID() == thread_id {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
val, _ := UseStates(ctx, []GraphNode{child}, func(states []NodeState) (interface{}, error) {
|
|
||||||
child_state := states[0].(ThreadState)
|
|
||||||
return checkIfChild(ctx, cur_id, child_state, child.ID()), nil
|
|
||||||
})
|
|
||||||
|
|
||||||
is_child := val.(bool)
|
|
||||||
if is_child {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
func LinkThreads(ctx * GraphContext, thread Thread, child Thread, info ThreadInfo) error {
|
|
||||||
if ctx == nil || thread == nil || child == nil {
|
|
||||||
return fmt.Errorf("invalid input")
|
|
||||||
}
|
|
||||||
|
|
||||||
if thread.ID() == child.ID() {
|
|
||||||
return fmt.Errorf("Will not link %s as a child of itself", thread.ID())
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
_, err := UpdateStates(ctx, []GraphNode{thread, child}, func(states []NodeState) ([]NodeState, interface{}, error) {
|
|
||||||
thread_state := states[0].(ThreadState)
|
|
||||||
child_state := states[1].(ThreadState)
|
|
||||||
|
|
||||||
if child_state.Parent() != nil {
|
|
||||||
return nil, nil, fmt.Errorf("EVENT_LINK_ERR: %s already has a parent, cannot link as child", child.ID())
|
|
||||||
}
|
|
||||||
|
|
||||||
if checkIfChild(ctx, thread.ID(), child_state, child.ID()) == true {
|
|
||||||
return nil, nil, fmt.Errorf("EVENT_LINK_ERR: %s is a child of %s so cannot add as parent", thread.ID(), child.ID())
|
|
||||||
}
|
|
||||||
|
|
||||||
if checkIfChild(ctx, child.ID(), thread_state, thread.ID()) == true {
|
|
||||||
return nil, nil, fmt.Errorf("EVENT_LINK_ERR: %s is already a parent of %s so will not add again", thread.ID(), child.ID())
|
|
||||||
}
|
|
||||||
|
|
||||||
err := thread_state.AddChild(child, info)
|
|
||||||
if err != nil {
|
|
||||||
return nil, nil, fmt.Errorf("EVENT_LINK_ERR: error adding %s as child to %s: %e", child.ID(), thread.ID(), err)
|
|
||||||
}
|
|
||||||
child_state.SetParent(thread)
|
|
||||||
|
|
||||||
return states, nil, nil
|
|
||||||
})
|
|
||||||
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// Thread is the interface that thread tree nodes must implement
|
|
||||||
type Thread interface {
|
|
||||||
Lockable
|
|
||||||
|
|
||||||
Action(action string) (ThreadAction, bool)
|
|
||||||
Handler(signal_type string) (ThreadHandler, bool)
|
|
||||||
|
|
||||||
SetTimeout(end_time time.Time, action string)
|
|
||||||
ClearTimeout()
|
|
||||||
Timeout() <-chan time.Time
|
|
||||||
TimeoutAction() string
|
|
||||||
}
|
|
||||||
|
|
||||||
func FindChild(ctx * GraphContext, thread Thread, thread_state ThreadState, id NodeID) Thread {
|
|
||||||
if thread == nil {
|
|
||||||
panic("cannot recurse through nil")
|
|
||||||
}
|
|
||||||
if id == thread.ID() {
|
|
||||||
return thread
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
for _, child := range thread_state.Children() {
|
|
||||||
res, _ := UseStates(ctx, []GraphNode{child}, func(states []NodeState) (interface{}, error) {
|
|
||||||
child_state := states[0].(ThreadState)
|
|
||||||
result := FindChild(ctx, child, child_state, id)
|
|
||||||
return result, nil
|
|
||||||
})
|
|
||||||
result := res.(Thread)
|
|
||||||
if result != nil {
|
|
||||||
return result
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func RunThread(ctx * GraphContext, thread Thread) error {
|
|
||||||
ctx.Log.Logf("thread", "EVENT_RUN: %s", thread.ID())
|
|
||||||
|
|
||||||
err := LockLockable(ctx, thread, thread, nil)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
_, err = UseStates(ctx, []GraphNode{thread}, func(states []NodeState) (interface{}, error) {
|
|
||||||
thread_state := states[0].(ThreadState)
|
|
||||||
if thread_state.Owner() == nil {
|
|
||||||
return nil, fmt.Errorf("EVENT_RUN_NOT_LOCKED: %s", thread_state.Name())
|
|
||||||
} else if thread_state.Owner().ID() != thread.ID() {
|
|
||||||
return nil, fmt.Errorf("EVENT_RUN_RESOURCE_ALREADY_LOCKED: %s, %s", thread_state.Name(), thread_state.Owner().ID())
|
|
||||||
}
|
|
||||||
return nil, nil
|
|
||||||
})
|
|
||||||
|
|
||||||
SendUpdate(ctx, thread, NewSignal(thread, "thread_start"))
|
|
||||||
|
|
||||||
next_action := "start"
|
|
||||||
for next_action != "" {
|
|
||||||
action, exists := thread.Action(next_action)
|
|
||||||
if exists == false {
|
|
||||||
error_str := fmt.Sprintf("%s is not a valid action", next_action)
|
|
||||||
return errors.New(error_str)
|
|
||||||
}
|
|
||||||
|
|
||||||
ctx.Log.Logf("thread", "EVENT_ACTION: %s - %s", thread.ID(), next_action)
|
|
||||||
next_action, err = action(ctx, thread)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
SendUpdate(ctx, thread, NewSignal(thread, "thread_done"))
|
|
||||||
|
|
||||||
ctx.Log.Logf("thread", "EVENT_RUN_DONE: %s", thread.ID())
|
|
||||||
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
type ThreadAction func(* GraphContext, Thread)(string, error)
|
|
||||||
type ThreadActions map[string]ThreadAction
|
|
||||||
type ThreadHandler func(* GraphContext, Thread, GraphSignal)(string, error)
|
|
||||||
type ThreadHandlers map[string]ThreadHandler
|
|
||||||
|
|
||||||
// Thread is the most basic thread that can exist in the thread tree.
|
|
||||||
// On start it automatically transitions to completion.
|
|
||||||
// This node by itself doesn't implement any special behaviours for children, so they will be ignored.
|
|
||||||
// When started, this thread automatically transitions to completion
|
|
||||||
type BaseThread struct {
|
|
||||||
BaseLockable
|
|
||||||
|
|
||||||
Actions ThreadActions
|
|
||||||
Handlers ThreadHandlers
|
|
||||||
|
|
||||||
timeout <-chan time.Time
|
|
||||||
timeout_action string
|
|
||||||
}
|
|
||||||
|
|
||||||
func (thread * BaseThread) Lock(node GraphNode, state LockableState) error {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (thread * BaseThread) Unlock(node GraphNode, state LockableState) error {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (thread * BaseThread) Action(action string) (ThreadAction, bool) {
|
|
||||||
action_fn, exists := thread.Actions[action]
|
|
||||||
return action_fn, exists
|
|
||||||
}
|
|
||||||
|
|
||||||
func (thread * BaseThread) Handler(signal_type string) (ThreadHandler, bool) {
|
|
||||||
handler, exists := thread.Handlers[signal_type]
|
|
||||||
return handler, exists
|
|
||||||
}
|
|
||||||
|
|
||||||
func (thread * BaseThread) TimeoutAction() string {
|
|
||||||
return thread.timeout_action
|
|
||||||
}
|
|
||||||
|
|
||||||
func (thread * BaseThread) Timeout() <-chan time.Time {
|
|
||||||
return thread.timeout
|
|
||||||
}
|
|
||||||
|
|
||||||
func (thread * BaseThread) ClearTimeout() {
|
|
||||||
thread.timeout_action = ""
|
|
||||||
thread.timeout = nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (thread * BaseThread) SetTimeout(end_time time.Time, action string) {
|
|
||||||
thread.timeout_action = action
|
|
||||||
thread.timeout = time.After(time.Until(end_time))
|
|
||||||
}
|
|
||||||
|
|
||||||
var ThreadDefaultStart = func(ctx * GraphContext, thread Thread) (string, error) {
|
|
||||||
ctx.Log.Logf("thread", "THREAD_DEFAUL_START: %s", thread.ID())
|
|
||||||
return "wait", nil
|
|
||||||
}
|
|
||||||
|
|
||||||
var ThreadWait = func(ctx * GraphContext, thread Thread) (string, error) {
|
|
||||||
ctx.Log.Logf("thread", "THREAD_WAIT: %s TIMEOUT: %+v", thread.ID(), thread.Timeout())
|
|
||||||
for {
|
|
||||||
select {
|
|
||||||
case signal := <- thread.SignalChannel():
|
|
||||||
ctx.Log.Logf("thread", "THREAD_SIGNAL: %s %+v", thread.ID(), signal)
|
|
||||||
if signal.Source() == thread.ID() {
|
|
||||||
ctx.Log.Logf("thread", "THREAD_SIGNAL_INTERNAL")
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
signal_fn, exists := thread.Handler(signal.Type())
|
|
||||||
if exists == true {
|
|
||||||
ctx.Log.Logf("thread", "THREAD_HANDLER: %s - %s", thread.ID(), signal.Type())
|
|
||||||
return signal_fn(ctx, thread, signal)
|
|
||||||
}
|
|
||||||
case <- thread.Timeout():
|
|
||||||
ctx.Log.Logf("thread", "THREAD_TIMEOUT %s - NEXT_STATE: %s", thread.ID(), thread.TimeoutAction())
|
|
||||||
return thread.TimeoutAction(), nil
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return "wait", nil
|
|
||||||
}
|
|
||||||
|
|
||||||
var ThreadAbort = func(ctx * GraphContext, thread Thread, signal GraphSignal) (string, error) {
|
|
||||||
return "", fmt.Errorf("%s aborted by signal from %s", thread.ID(), signal.Source())
|
|
||||||
}
|
|
||||||
|
|
||||||
var ThreadCancel = func(ctx * GraphContext, thread Thread, signal GraphSignal) (string, error) {
|
|
||||||
return "", nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewBaseThreadState(name string) BaseThreadState {
|
|
||||||
return BaseThreadState{
|
|
||||||
BaseLockableState: NewBaseLockableState(name),
|
|
||||||
children: []Thread{},
|
|
||||||
child_info: map[NodeID]ThreadInfo{},
|
|
||||||
parent: nil,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewBaseThread(ctx * GraphContext, actions ThreadActions, handlers ThreadHandlers, state ThreadState) (BaseThread, error) {
|
|
||||||
thread := BaseThread{
|
|
||||||
BaseLockable: BaseLockable{BaseNode: NewNode(ctx, RandID(), state)},
|
|
||||||
Actions: ThreadActions{
|
|
||||||
"wait": ThreadWait,
|
|
||||||
"start": ThreadDefaultStart,
|
|
||||||
},
|
|
||||||
Handlers: ThreadHandlers{
|
|
||||||
"abort": ThreadAbort,
|
|
||||||
"cancel": ThreadCancel,
|
|
||||||
},
|
|
||||||
timeout: nil,
|
|
||||||
timeout_action: "",
|
|
||||||
}
|
|
||||||
|
|
||||||
for key, fn := range(actions) {
|
|
||||||
thread.Actions[key] = fn
|
|
||||||
}
|
|
||||||
|
|
||||||
for key, fn := range(handlers) {
|
|
||||||
thread.Handlers[key] = fn
|
|
||||||
}
|
|
||||||
|
|
||||||
return thread, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewSimpleBaseThread(ctx * GraphContext, name string, requirements []Lockable, actions ThreadActions, handlers ThreadHandlers) (* BaseThread, error) {
|
|
||||||
state := NewBaseThreadState(name)
|
|
||||||
thread, err := NewBaseThread(ctx, actions, handlers, &state)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
thread_ptr := &thread
|
|
||||||
|
|
||||||
err = LinkLockables(ctx, thread_ptr, requirements)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
return thread_ptr, nil
|
|
||||||
}
|
|
@ -1,76 +0,0 @@
|
|||||||
package graphvent
|
|
||||||
|
|
||||||
import (
|
|
||||||
"testing"
|
|
||||||
"time"
|
|
||||||
"encoding/json"
|
|
||||||
"fmt"
|
|
||||||
)
|
|
||||||
|
|
||||||
func TestNewEvent(t * testing.T) {
|
|
||||||
ctx := testContext(t)
|
|
||||||
|
|
||||||
t1, err := NewSimpleBaseThread(ctx, "Test thread 1", []Lockable{}, ThreadActions{}, ThreadHandlers{})
|
|
||||||
fatalErr(t, err)
|
|
||||||
|
|
||||||
go func(thread Thread) {
|
|
||||||
time.Sleep(10*time.Millisecond)
|
|
||||||
SendUpdate(ctx, t1, CancelSignal(nil))
|
|
||||||
}(t1)
|
|
||||||
|
|
||||||
err = RunThread(ctx, t1)
|
|
||||||
fatalErr(t, err)
|
|
||||||
|
|
||||||
_, err = UseStates(ctx, []GraphNode{t1}, func(states []NodeState) (interface{}, error) {
|
|
||||||
ser, err := json.MarshalIndent(states, "", " ")
|
|
||||||
fatalErr(t, err)
|
|
||||||
|
|
||||||
fmt.Printf("\n%s\n", ser)
|
|
||||||
|
|
||||||
return nil, nil
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestEventWithRequirement(t * testing.T) {
|
|
||||||
ctx := logTestContext(t, []string{"lockable", "thread"})
|
|
||||||
|
|
||||||
l1, err := NewLockable(ctx, "Test Lockable 1", []Lockable{})
|
|
||||||
fatalErr(t, err)
|
|
||||||
|
|
||||||
t1, err := NewSimpleBaseThread(ctx, "Test Thread 1", []Lockable{l1}, ThreadActions{}, ThreadHandlers{})
|
|
||||||
fatalErr(t, err)
|
|
||||||
|
|
||||||
go func (thread Thread) {
|
|
||||||
time.Sleep(10*time.Millisecond)
|
|
||||||
_, err := UseStates(ctx, []GraphNode{l1}, func(states []NodeState) (interface{}, error) {
|
|
||||||
ser, err := json.MarshalIndent(states[0], "", " ")
|
|
||||||
fatalErr(t, err)
|
|
||||||
|
|
||||||
fmt.Printf("\n%s\n", ser)
|
|
||||||
return nil, nil
|
|
||||||
})
|
|
||||||
fatalErr(t, err)
|
|
||||||
SendUpdate(ctx, t1, CancelSignal(nil))
|
|
||||||
}(t1)
|
|
||||||
fatalErr(t, err)
|
|
||||||
|
|
||||||
err = RunThread(ctx, t1)
|
|
||||||
fatalErr(t, err)
|
|
||||||
|
|
||||||
_, err = UseStates(ctx, []GraphNode{l1}, func(states []NodeState) (interface{}, error) {
|
|
||||||
ser, err := json.MarshalIndent(states[0], "", " ")
|
|
||||||
fatalErr(t, err)
|
|
||||||
|
|
||||||
fmt.Printf("\n%s\n", ser)
|
|
||||||
return nil, nil
|
|
||||||
})
|
|
||||||
fatalErr(t, err)
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestCustomEventState(t * testing.T ) {
|
|
||||||
ctx := logTestContext(t, []string{"lockable", "thread"})
|
|
||||||
|
|
||||||
t1, err := NewSimpleBaseThread(ctx, "Test Thread 1", []Lockable{}, ThreadActions{}, ThreadHandlers{})
|
|
||||||
fatalErr(t, err)
|
|
||||||
println(t1)
|
|
||||||
}
|
|
Loading…
Reference in New Issue