···11+ GNU AFFERO GENERAL PUBLIC LICENSE
22+ Version 3, 19 November 2007
33+44+ Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
55+ Everyone is permitted to copy and distribute verbatim copies
66+ of this license document, but changing it is not allowed.
77+88+ Preamble
99+1010+ The GNU Affero General Public License is a free, copyleft license for
1111+software and other kinds of works, specifically designed to ensure
1212+cooperation with the community in the case of network server software.
1313+1414+ The licenses for most software and other practical works are designed
1515+to take away your freedom to share and change the works. By contrast,
1616+our General Public Licenses are intended to guarantee your freedom to
1717+share and change all versions of a program--to make sure it remains free
1818+software for all its users.
1919+2020+ When we speak of free software, we are referring to freedom, not
2121+price. Our General Public Licenses are designed to make sure that you
2222+have the freedom to distribute copies of free software (and charge for
2323+them if you wish), that you receive source code or can get it if you
2424+want it, that you can change the software or use pieces of it in new
2525+free programs, and that you know you can do these things.
2626+2727+ Developers that use our General Public Licenses protect your rights
2828+with two steps: (1) assert copyright on the software, and (2) offer
2929+you this License which gives you legal permission to copy, distribute
3030+and/or modify the software.
3131+3232+ A secondary benefit of defending all users' freedom is that
3333+improvements made in alternate versions of the program, if they
3434+receive widespread use, become available for other developers to
3535+incorporate. Many developers of free software are heartened and
3636+encouraged by the resulting cooperation. However, in the case of
3737+software used on network servers, this result may fail to come about.
3838+The GNU General Public License permits making a modified version and
3939+letting the public access it on a server without ever releasing its
4040+source code to the public.
4141+4242+ The GNU Affero General Public License is designed specifically to
4343+ensure that, in such cases, the modified source code becomes available
4444+to the community. It requires the operator of a network server to
4545+provide the source code of the modified version running there to the
4646+users of that server. Therefore, public use of a modified version, on
4747+a publicly accessible server, gives the public access to the source
4848+code of the modified version.
4949+5050+ An older license, called the Affero General Public License and
5151+published by Affero, was designed to accomplish similar goals. This is
5252+a different license, not a version of the Affero GPL, but Affero has
5353+released a new version of the Affero GPL which permits relicensing under
5454+this license.
5555+5656+ The precise terms and conditions for copying, distribution and
5757+modification follow.
5858+5959+ TERMS AND CONDITIONS
6060+6161+ 0. Definitions.
6262+6363+ "This License" refers to version 3 of the GNU Affero General Public License.
6464+6565+ "Copyright" also means copyright-like laws that apply to other kinds of
6666+works, such as semiconductor masks.
6767+6868+ "The Program" refers to any copyrightable work licensed under this
6969+License. Each licensee is addressed as "you". "Licensees" and
7070+"recipients" may be individuals or organizations.
7171+7272+ To "modify" a work means to copy from or adapt all or part of the work
7373+in a fashion requiring copyright permission, other than the making of an
7474+exact copy. The resulting work is called a "modified version" of the
7575+earlier work or a work "based on" the earlier work.
7676+7777+ A "covered work" means either the unmodified Program or a work based
7878+on the Program.
7979+8080+ To "propagate" a work means to do anything with it that, without
8181+permission, would make you directly or secondarily liable for
8282+infringement under applicable copyright law, except executing it on a
8383+computer or modifying a private copy. Propagation includes copying,
8484+distribution (with or without modification), making available to the
8585+public, and in some countries other activities as well.
8686+8787+ To "convey" a work means any kind of propagation that enables other
8888+parties to make or receive copies. Mere interaction with a user through
8989+a computer network, with no transfer of a copy, is not conveying.
9090+9191+ An interactive user interface displays "Appropriate Legal Notices"
9292+to the extent that it includes a convenient and prominently visible
9393+feature that (1) displays an appropriate copyright notice, and (2)
9494+tells the user that there is no warranty for the work (except to the
9595+extent that warranties are provided), that licensees may convey the
9696+work under this License, and how to view a copy of this License. If
9797+the interface presents a list of user commands or options, such as a
9898+menu, a prominent item in the list meets this criterion.
9999+100100+ 1. Source Code.
101101+102102+ The "source code" for a work means the preferred form of the work
103103+for making modifications to it. "Object code" means any non-source
104104+form of a work.
105105+106106+ A "Standard Interface" means an interface that either is an official
107107+standard defined by a recognized standards body, or, in the case of
108108+interfaces specified for a particular programming language, one that
109109+is widely used among developers working in that language.
110110+111111+ The "System Libraries" of an executable work include anything, other
112112+than the work as a whole, that (a) is included in the normal form of
113113+packaging a Major Component, but which is not part of that Major
114114+Component, and (b) serves only to enable use of the work with that
115115+Major Component, or to implement a Standard Interface for which an
116116+implementation is available to the public in source code form. A
117117+"Major Component", in this context, means a major essential component
118118+(kernel, window system, and so on) of the specific operating system
119119+(if any) on which the executable work runs, or a compiler used to
120120+produce the work, or an object code interpreter used to run it.
121121+122122+ The "Corresponding Source" for a work in object code form means all
123123+the source code needed to generate, install, and (for an executable
124124+work) run the object code and to modify the work, including scripts to
125125+control those activities. However, it does not include the work's
126126+System Libraries, or general-purpose tools or generally available free
127127+programs which are used unmodified in performing those activities but
128128+which are not part of the work. For example, Corresponding Source
129129+includes interface definition files associated with source files for
130130+the work, and the source code for shared libraries and dynamically
131131+linked subprograms that the work is specifically designed to require,
132132+such as by intimate data communication or control flow between those
133133+subprograms and other parts of the work.
134134+135135+ The Corresponding Source need not include anything that users
136136+can regenerate automatically from other parts of the Corresponding
137137+Source.
138138+139139+ The Corresponding Source for a work in source code form is that
140140+same work.
141141+142142+ 2. Basic Permissions.
143143+144144+ All rights granted under this License are granted for the term of
145145+copyright on the Program, and are irrevocable provided the stated
146146+conditions are met. This License explicitly affirms your unlimited
147147+permission to run the unmodified Program. The output from running a
148148+covered work is covered by this License only if the output, given its
149149+content, constitutes a covered work. This License acknowledges your
150150+rights of fair use or other equivalent, as provided by copyright law.
151151+152152+ You may make, run and propagate covered works that you do not
153153+convey, without conditions so long as your license otherwise remains
154154+in force. You may convey covered works to others for the sole purpose
155155+of having them make modifications exclusively for you, or provide you
156156+with facilities for running those works, provided that you comply with
157157+the terms of this License in conveying all material for which you do
158158+not control copyright. Those thus making or running the covered works
159159+for you must do so exclusively on your behalf, under your direction
160160+and control, on terms that prohibit them from making any copies of
161161+your copyrighted material outside their relationship with you.
162162+163163+ Conveying under any other circumstances is permitted solely under
164164+the conditions stated below. Sublicensing is not allowed; section 10
165165+makes it unnecessary.
166166+167167+ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
168168+169169+ No covered work shall be deemed part of an effective technological
170170+measure under any applicable law fulfilling obligations under article
171171+11 of the WIPO copyright treaty adopted on 20 December 1996, or
172172+similar laws prohibiting or restricting circumvention of such
173173+measures.
174174+175175+ When you convey a covered work, you waive any legal power to forbid
176176+circumvention of technological measures to the extent such circumvention
177177+is effected by exercising rights under this License with respect to
178178+the covered work, and you disclaim any intention to limit operation or
179179+modification of the work as a means of enforcing, against the work's
180180+users, your or third parties' legal rights to forbid circumvention of
181181+technological measures.
182182+183183+ 4. Conveying Verbatim Copies.
184184+185185+ You may convey verbatim copies of the Program's source code as you
186186+receive it, in any medium, provided that you conspicuously and
187187+appropriately publish on each copy an appropriate copyright notice;
188188+keep intact all notices stating that this License and any
189189+non-permissive terms added in accord with section 7 apply to the code;
190190+keep intact all notices of the absence of any warranty; and give all
191191+recipients a copy of this License along with the Program.
192192+193193+ You may charge any price or no price for each copy that you convey,
194194+and you may offer support or warranty protection for a fee.
195195+196196+ 5. Conveying Modified Source Versions.
197197+198198+ You may convey a work based on the Program, or the modifications to
199199+produce it from the Program, in the form of source code under the
200200+terms of section 4, provided that you also meet all of these conditions:
201201+202202+ a) The work must carry prominent notices stating that you modified
203203+ it, and giving a relevant date.
204204+205205+ b) The work must carry prominent notices stating that it is
206206+ released under this License and any conditions added under section
207207+ 7. This requirement modifies the requirement in section 4 to
208208+ "keep intact all notices".
209209+210210+ c) You must license the entire work, as a whole, under this
211211+ License to anyone who comes into possession of a copy. This
212212+ License will therefore apply, along with any applicable section 7
213213+ additional terms, to the whole of the work, and all its parts,
214214+ regardless of how they are packaged. This License gives no
215215+ permission to license the work in any other way, but it does not
216216+ invalidate such permission if you have separately received it.
217217+218218+ d) If the work has interactive user interfaces, each must display
219219+ Appropriate Legal Notices; however, if the Program has interactive
220220+ interfaces that do not display Appropriate Legal Notices, your
221221+ work need not make them do so.
222222+223223+ A compilation of a covered work with other separate and independent
224224+works, which are not by their nature extensions of the covered work,
225225+and which are not combined with it such as to form a larger program,
226226+in or on a volume of a storage or distribution medium, is called an
227227+"aggregate" if the compilation and its resulting copyright are not
228228+used to limit the access or legal rights of the compilation's users
229229+beyond what the individual works permit. Inclusion of a covered work
230230+in an aggregate does not cause this License to apply to the other
231231+parts of the aggregate.
232232+233233+ 6. Conveying Non-Source Forms.
234234+235235+ You may convey a covered work in object code form under the terms
236236+of sections 4 and 5, provided that you also convey the
237237+machine-readable Corresponding Source under the terms of this License,
238238+in one of these ways:
239239+240240+ a) Convey the object code in, or embodied in, a physical product
241241+ (including a physical distribution medium), accompanied by the
242242+ Corresponding Source fixed on a durable physical medium
243243+ customarily used for software interchange.
244244+245245+ b) Convey the object code in, or embodied in, a physical product
246246+ (including a physical distribution medium), accompanied by a
247247+ written offer, valid for at least three years and valid for as
248248+ long as you offer spare parts or customer support for that product
249249+ model, to give anyone who possesses the object code either (1) a
250250+ copy of the Corresponding Source for all the software in the
251251+ product that is covered by this License, on a durable physical
252252+ medium customarily used for software interchange, for a price no
253253+ more than your reasonable cost of physically performing this
254254+ conveying of source, or (2) access to copy the
255255+ Corresponding Source from a network server at no charge.
256256+257257+ c) Convey individual copies of the object code with a copy of the
258258+ written offer to provide the Corresponding Source. This
259259+ alternative is allowed only occasionally and noncommercially, and
260260+ only if you received the object code with such an offer, in accord
261261+ with subsection 6b.
262262+263263+ d) Convey the object code by offering access from a designated
264264+ place (gratis or for a charge), and offer equivalent access to the
265265+ Corresponding Source in the same way through the same place at no
266266+ further charge. You need not require recipients to copy the
267267+ Corresponding Source along with the object code. If the place to
268268+ copy the object code is a network server, the Corresponding Source
269269+ may be on a different server (operated by you or a third party)
270270+ that supports equivalent copying facilities, provided you maintain
271271+ clear directions next to the object code saying where to find the
272272+ Corresponding Source. Regardless of what server hosts the
273273+ Corresponding Source, you remain obligated to ensure that it is
274274+ available for as long as needed to satisfy these requirements.
275275+276276+ e) Convey the object code using peer-to-peer transmission, provided
277277+ you inform other peers where the object code and Corresponding
278278+ Source of the work are being offered to the general public at no
279279+ charge under subsection 6d.
280280+281281+ A separable portion of the object code, whose source code is excluded
282282+from the Corresponding Source as a System Library, need not be
283283+included in conveying the object code work.
284284+285285+ A "User Product" is either (1) a "consumer product", which means any
286286+tangible personal property which is normally used for personal, family,
287287+or household purposes, or (2) anything designed or sold for incorporation
288288+into a dwelling. In determining whether a product is a consumer product,
289289+doubtful cases shall be resolved in favor of coverage. For a particular
290290+product received by a particular user, "normally used" refers to a
291291+typical or common use of that class of product, regardless of the status
292292+of the particular user or of the way in which the particular user
293293+actually uses, or expects or is expected to use, the product. A product
294294+is a consumer product regardless of whether the product has substantial
295295+commercial, industrial or non-consumer uses, unless such uses represent
296296+the only significant mode of use of the product.
297297+298298+ "Installation Information" for a User Product means any methods,
299299+procedures, authorization keys, or other information required to install
300300+and execute modified versions of a covered work in that User Product from
301301+a modified version of its Corresponding Source. The information must
302302+suffice to ensure that the continued functioning of the modified object
303303+code is in no case prevented or interfered with solely because
304304+modification has been made.
305305+306306+ If you convey an object code work under this section in, or with, or
307307+specifically for use in, a User Product, and the conveying occurs as
308308+part of a transaction in which the right of possession and use of the
309309+User Product is transferred to the recipient in perpetuity or for a
310310+fixed term (regardless of how the transaction is characterized), the
311311+Corresponding Source conveyed under this section must be accompanied
312312+by the Installation Information. But this requirement does not apply
313313+if neither you nor any third party retains the ability to install
314314+modified object code on the User Product (for example, the work has
315315+been installed in ROM).
316316+317317+ The requirement to provide Installation Information does not include a
318318+requirement to continue to provide support service, warranty, or updates
319319+for a work that has been modified or installed by the recipient, or for
320320+the User Product in which it has been modified or installed. Access to a
321321+network may be denied when the modification itself materially and
322322+adversely affects the operation of the network or violates the rules and
323323+protocols for communication across the network.
324324+325325+ Corresponding Source conveyed, and Installation Information provided,
326326+in accord with this section must be in a format that is publicly
327327+documented (and with an implementation available to the public in
328328+source code form), and must require no special password or key for
329329+unpacking, reading or copying.
330330+331331+ 7. Additional Terms.
332332+333333+ "Additional permissions" are terms that supplement the terms of this
334334+License by making exceptions from one or more of its conditions.
335335+Additional permissions that are applicable to the entire Program shall
336336+be treated as though they were included in this License, to the extent
337337+that they are valid under applicable law. If additional permissions
338338+apply only to part of the Program, that part may be used separately
339339+under those permissions, but the entire Program remains governed by
340340+this License without regard to the additional permissions.
341341+342342+ When you convey a copy of a covered work, you may at your option
343343+remove any additional permissions from that copy, or from any part of
344344+it. (Additional permissions may be written to require their own
345345+removal in certain cases when you modify the work.) You may place
346346+additional permissions on material, added by you to a covered work,
347347+for which you have or can give appropriate copyright permission.
348348+349349+ Notwithstanding any other provision of this License, for material you
350350+add to a covered work, you may (if authorized by the copyright holders of
351351+that material) supplement the terms of this License with terms:
352352+353353+ a) Disclaiming warranty or limiting liability differently from the
354354+ terms of sections 15 and 16 of this License; or
355355+356356+ b) Requiring preservation of specified reasonable legal notices or
357357+ author attributions in that material or in the Appropriate Legal
358358+ Notices displayed by works containing it; or
359359+360360+ c) Prohibiting misrepresentation of the origin of that material, or
361361+ requiring that modified versions of such material be marked in
362362+ reasonable ways as different from the original version; or
363363+364364+ d) Limiting the use for publicity purposes of names of licensors or
365365+ authors of the material; or
366366+367367+ e) Declining to grant rights under trademark law for use of some
368368+ trade names, trademarks, or service marks; or
369369+370370+ f) Requiring indemnification of licensors and authors of that
371371+ material by anyone who conveys the material (or modified versions of
372372+ it) with contractual assumptions of liability to the recipient, for
373373+ any liability that these contractual assumptions directly impose on
374374+ those licensors and authors.
375375+376376+ All other non-permissive additional terms are considered "further
377377+restrictions" within the meaning of section 10. If the Program as you
378378+received it, or any part of it, contains a notice stating that it is
379379+governed by this License along with a term that is a further
380380+restriction, you may remove that term. If a license document contains
381381+a further restriction but permits relicensing or conveying under this
382382+License, you may add to a covered work material governed by the terms
383383+of that license document, provided that the further restriction does
384384+not survive such relicensing or conveying.
385385+386386+ If you add terms to a covered work in accord with this section, you
387387+must place, in the relevant source files, a statement of the
388388+additional terms that apply to those files, or a notice indicating
389389+where to find the applicable terms.
390390+391391+ Additional terms, permissive or non-permissive, may be stated in the
392392+form of a separately written license, or stated as exceptions;
393393+the above requirements apply either way.
394394+395395+ 8. Termination.
396396+397397+ You may not propagate or modify a covered work except as expressly
398398+provided under this License. Any attempt otherwise to propagate or
399399+modify it is void, and will automatically terminate your rights under
400400+this License (including any patent licenses granted under the third
401401+paragraph of section 11).
402402+403403+ However, if you cease all violation of this License, then your
404404+license from a particular copyright holder is reinstated (a)
405405+provisionally, unless and until the copyright holder explicitly and
406406+finally terminates your license, and (b) permanently, if the copyright
407407+holder fails to notify you of the violation by some reasonable means
408408+prior to 60 days after the cessation.
409409+410410+ Moreover, your license from a particular copyright holder is
411411+reinstated permanently if the copyright holder notifies you of the
412412+violation by some reasonable means, this is the first time you have
413413+received notice of violation of this License (for any work) from that
414414+copyright holder, and you cure the violation prior to 30 days after
415415+your receipt of the notice.
416416+417417+ Termination of your rights under this section does not terminate the
418418+licenses of parties who have received copies or rights from you under
419419+this License. If your rights have been terminated and not permanently
420420+reinstated, you do not qualify to receive new licenses for the same
421421+material under section 10.
422422+423423+ 9. Acceptance Not Required for Having Copies.
424424+425425+ You are not required to accept this License in order to receive or
426426+run a copy of the Program. Ancillary propagation of a covered work
427427+occurring solely as a consequence of using peer-to-peer transmission
428428+to receive a copy likewise does not require acceptance. However,
429429+nothing other than this License grants you permission to propagate or
430430+modify any covered work. These actions infringe copyright if you do
431431+not accept this License. Therefore, by modifying or propagating a
432432+covered work, you indicate your acceptance of this License to do so.
433433+434434+ 10. Automatic Licensing of Downstream Recipients.
435435+436436+ Each time you convey a covered work, the recipient automatically
437437+receives a license from the original licensors, to run, modify and
438438+propagate that work, subject to this License. You are not responsible
439439+for enforcing compliance by third parties with this License.
440440+441441+ An "entity transaction" is a transaction transferring control of an
442442+organization, or substantially all assets of one, or subdividing an
443443+organization, or merging organizations. If propagation of a covered
444444+work results from an entity transaction, each party to that
445445+transaction who receives a copy of the work also receives whatever
446446+licenses to the work the party's predecessor in interest had or could
447447+give under the previous paragraph, plus a right to possession of the
448448+Corresponding Source of the work from the predecessor in interest, if
449449+the predecessor has it or can get it with reasonable efforts.
450450+451451+ You may not impose any further restrictions on the exercise of the
452452+rights granted or affirmed under this License. For example, you may
453453+not impose a license fee, royalty, or other charge for exercise of
454454+rights granted under this License, and you may not initiate litigation
455455+(including a cross-claim or counterclaim in a lawsuit) alleging that
456456+any patent claim is infringed by making, using, selling, offering for
457457+sale, or importing the Program or any portion of it.
458458+459459+ 11. Patents.
460460+461461+ A "contributor" is a copyright holder who authorizes use under this
462462+License of the Program or a work on which the Program is based. The
463463+work thus licensed is called the contributor's "contributor version".
464464+465465+ A contributor's "essential patent claims" are all patent claims
466466+owned or controlled by the contributor, whether already acquired or
467467+hereafter acquired, that would be infringed by some manner, permitted
468468+by this License, of making, using, or selling its contributor version,
469469+but do not include claims that would be infringed only as a
470470+consequence of further modification of the contributor version. For
471471+purposes of this definition, "control" includes the right to grant
472472+patent sublicenses in a manner consistent with the requirements of
473473+this License.
474474+475475+ Each contributor grants you a non-exclusive, worldwide, royalty-free
476476+patent license under the contributor's essential patent claims, to
477477+make, use, sell, offer for sale, import and otherwise run, modify and
478478+propagate the contents of its contributor version.
479479+480480+ In the following three paragraphs, a "patent license" is any express
481481+agreement or commitment, however denominated, not to enforce a patent
482482+(such as an express permission to practice a patent or covenant not to
483483+sue for patent infringement). To "grant" such a patent license to a
484484+party means to make such an agreement or commitment not to enforce a
485485+patent against the party.
486486+487487+ If you convey a covered work, knowingly relying on a patent license,
488488+and the Corresponding Source of the work is not available for anyone
489489+to copy, free of charge and under the terms of this License, through a
490490+publicly available network server or other readily accessible means,
491491+then you must either (1) cause the Corresponding Source to be so
492492+available, or (2) arrange to deprive yourself of the benefit of the
493493+patent license for this particular work, or (3) arrange, in a manner
494494+consistent with the requirements of this License, to extend the patent
495495+license to downstream recipients. "Knowingly relying" means you have
496496+actual knowledge that, but for the patent license, your conveying the
497497+covered work in a country, or your recipient's use of the covered work
498498+in a country, would infringe one or more identifiable patents in that
499499+country that you have reason to believe are valid.
500500+501501+ If, pursuant to or in connection with a single transaction or
502502+arrangement, you convey, or propagate by procuring conveyance of, a
503503+covered work, and grant a patent license to some of the parties
504504+receiving the covered work authorizing them to use, propagate, modify
505505+or convey a specific copy of the covered work, then the patent license
506506+you grant is automatically extended to all recipients of the covered
507507+work and works based on it.
508508+509509+ A patent license is "discriminatory" if it does not include within
510510+the scope of its coverage, prohibits the exercise of, or is
511511+conditioned on the non-exercise of one or more of the rights that are
512512+specifically granted under this License. You may not convey a covered
513513+work if you are a party to an arrangement with a third party that is
514514+in the business of distributing software, under which you make payment
515515+to the third party based on the extent of your activity of conveying
516516+the work, and under which the third party grants, to any of the
517517+parties who would receive the covered work from you, a discriminatory
518518+patent license (a) in connection with copies of the covered work
519519+conveyed by you (or copies made from those copies), or (b) primarily
520520+for and in connection with specific products or compilations that
521521+contain the covered work, unless you entered into that arrangement,
522522+or that patent license was granted, prior to 28 March 2007.
523523+524524+ Nothing in this License shall be construed as excluding or limiting
525525+any implied license or other defenses to infringement that may
526526+otherwise be available to you under applicable patent law.
527527+528528+ 12. No Surrender of Others' Freedom.
529529+530530+ If conditions are imposed on you (whether by court order, agreement or
531531+otherwise) that contradict the conditions of this License, they do not
532532+excuse you from the conditions of this License. If you cannot convey a
533533+covered work so as to satisfy simultaneously your obligations under this
534534+License and any other pertinent obligations, then as a consequence you may
535535+not convey it at all. For example, if you agree to terms that obligate you
536536+to collect a royalty for further conveying from those to whom you convey
537537+the Program, the only way you could satisfy both those terms and this
538538+License would be to refrain entirely from conveying the Program.
539539+540540+ 13. Remote Network Interaction; Use with the GNU General Public License.
541541+542542+ Notwithstanding any other provision of this License, if you modify the
543543+Program, your modified version must prominently offer all users
544544+interacting with it remotely through a computer network (if your version
545545+supports such interaction) an opportunity to receive the Corresponding
546546+Source of your version by providing access to the Corresponding Source
547547+from a network server at no charge, through some standard or customary
548548+means of facilitating copying of software. This Corresponding Source
549549+shall include the Corresponding Source for any work covered by version 3
550550+of the GNU General Public License that is incorporated pursuant to the
551551+following paragraph.
552552+553553+ Notwithstanding any other provision of this License, you have
554554+permission to link or combine any covered work with a work licensed
555555+under version 3 of the GNU General Public License into a single
556556+combined work, and to convey the resulting work. The terms of this
557557+License will continue to apply to the part which is the covered work,
558558+but the work with which it is combined will remain governed by version
559559+3 of the GNU General Public License.
560560+561561+ 14. Revised Versions of this License.
562562+563563+ The Free Software Foundation may publish revised and/or new versions of
564564+the GNU Affero General Public License from time to time. Such new versions
565565+will be similar in spirit to the present version, but may differ in detail to
566566+address new problems or concerns.
567567+568568+ Each version is given a distinguishing version number. If the
569569+Program specifies that a certain numbered version of the GNU Affero General
570570+Public License "or any later version" applies to it, you have the
571571+option of following the terms and conditions either of that numbered
572572+version or of any later version published by the Free Software
573573+Foundation. If the Program does not specify a version number of the
574574+GNU Affero General Public License, you may choose any version ever published
575575+by the Free Software Foundation.
576576+577577+ If the Program specifies that a proxy can decide which future
578578+versions of the GNU Affero General Public License can be used, that proxy's
579579+public statement of acceptance of a version permanently authorizes you
580580+to choose that version for the Program.
581581+582582+ Later license versions may give you additional or different
583583+permissions. However, no additional obligations are imposed on any
584584+author or copyright holder as a result of your choosing to follow a
585585+later version.
586586+587587+ 15. Disclaimer of Warranty.
588588+589589+ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
590590+APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
591591+HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
592592+OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
593593+THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
594594+PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
595595+IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
596596+ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
597597+598598+ 16. Limitation of Liability.
599599+600600+ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
601601+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
602602+THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
603603+GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
604604+USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
605605+DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
606606+PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
607607+EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
608608+SUCH DAMAGES.
609609+610610+ 17. Interpretation of Sections 15 and 16.
611611+612612+ If the disclaimer of warranty and limitation of liability provided
613613+above cannot be given local legal effect according to their terms,
614614+reviewing courts shall apply local law that most closely approximates
615615+an absolute waiver of all civil liability in connection with the
616616+Program, unless a warranty or assumption of liability accompanies a
617617+copy of the Program in return for a fee.
618618+619619+ END OF TERMS AND CONDITIONS
620620+621621+ How to Apply These Terms to Your New Programs
622622+623623+ If you develop a new program, and you want it to be of the greatest
624624+possible use to the public, the best way to achieve this is to make it
625625+free software which everyone can redistribute and change under these terms.
626626+627627+ To do so, attach the following notices to the program. It is safest
628628+to attach them to the start of each source file to most effectively
629629+state the exclusion of warranty; and each file should have at least
630630+the "copyright" line and a pointer to where the full notice is found.
631631+632632+ <one line to give the program's name and a brief idea of what it does.>
633633+ Copyright (C) <year> <name of author>
634634+635635+ This program is free software: you can redistribute it and/or modify
636636+ it under the terms of the GNU Affero General Public License as published
637637+ by the Free Software Foundation, either version 3 of the License, or
638638+ (at your option) any later version.
639639+640640+ This program is distributed in the hope that it will be useful,
641641+ but WITHOUT ANY WARRANTY; without even the implied warranty of
642642+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
643643+ GNU Affero General Public License for more details.
644644+645645+ You should have received a copy of the GNU Affero General Public License
646646+ along with this program. If not, see <https://www.gnu.org/licenses/>.
647647+648648+Also add information on how to contact you by electronic and paper mail.
649649+650650+ If your software can interact with users remotely through a computer
651651+network, you should also make sure that it provides a way for users to
652652+get its source. For example, if your program is a web application, its
653653+interface could display a "Source" link that leads users to an archive
654654+of the code. There are many ways you could offer source, and different
655655+solutions will be better for different programs; see section 13 for the
656656+specific requirements.
657657+658658+ You should also get your employer (if you work as a programmer) or school,
659659+if any, to sign a "copyright disclaimer" for the program, if necessary.
660660+For more information on this, and how to apply and follow the GNU AGPL, see
661661+<https://www.gnu.org/licenses/>.
+3
constellation/LICENSE.future
···11+constellation's source code is currently only available under the AGPL license.
22+33+it MAY be relicensed in the future to MIT and/or Apache 2.0, at the sole discretion of the microcosm organization, but is not available under these licenses today.
+9
constellation/readme.md
···8383```
848485858686+## Contributions
8787+8888+### Licensing
8989+9090+Constellation's source code is currently available exclusively under the AGPL license (see [LICENSE](./LICENSE)).
9191+9292+In the future, its code MAY become available under the MIT and/or Apache2.0 licenses, at the sole discretion of the microcosm organization. Contributing implies acceptance with this possible future licensing change. The change has not happed yet and is not guaranteed.
9393+9494+8695some todos
87968897- [x] find links and write them to rocksdb
+246-62
constellation/src/bin/main.rs
···11use anyhow::{bail, Result};
22use clap::{Parser, ValueEnum};
33+use metrics::{describe_counter, describe_gauge, describe_histogram, Unit};
34use metrics_exporter_prometheus::PrometheusBuilder;
55+use std::net::SocketAddr;
46use std::num::NonZero;
57use std::path::PathBuf;
68use std::sync::{atomic::AtomicU32, Arc};
···2123#[derive(Parser, Debug)]
2224#[command(version, about, long_about = None)]
2325struct Args {
2424- #[arg(short, long)]
2626+ /// constellation server's listen address
2727+ #[arg(long)]
2828+ #[clap(default_value = "0.0.0.0:6789")]
2929+ bind: SocketAddr,
3030+ /// enable metrics collection and serving
3131+ #[arg(long, action)]
3232+ collect_metrics: bool,
3333+ /// metrics server's listen address
3434+ #[arg(long, requires("collect_metrics"))]
3535+ #[clap(default_value = "0.0.0.0:8765")]
3636+ bind_metrics: SocketAddr,
2537 /// Jetstream server to connect to (exclusive with --fixture). Provide either a wss:// URL, or a shorhand value:
2638 /// 'us-east-1', 'us-east-2', 'us-west-1', or 'us-west-2'
2739 #[arg(short, long)]
···3446 #[arg(short, long)]
3547 #[clap(value_enum, default_value_t = StorageBackend::Memory)]
3648 backend: StorageBackend,
4949+ /// Serve a did:web document for this domain
5050+ #[arg(long)]
5151+ did_web_domain: Option<String>,
3752 /// Initiate a database backup into this dir, if supported by the storage
3853 #[arg(long)]
3954 backup: Option<PathBuf>,
···4661 /// Saved jsonl from jetstream to use instead of a live subscription
4762 #[arg(short, long)]
4863 fixture: Option<PathBuf>,
6464+ /// Don't change the database jetstream cursor when using a fixture
6565+ #[arg(long, requires("fixture"))]
6666+ fixture_preserve_cursor: bool,
6767+ /// fix the constellation start date (funny previous bug oops)
6868+ #[arg(long, action)]
6969+ reset_db_start: bool,
7070+ /// debugging: print the current jetstream cursor and exit
7171+ #[arg(long, action)]
7272+ print_cursor: bool,
4973}
50745175#[derive(Debug, Clone, ValueEnum)]
···6892fn main() -> Result<()> {
6993 let args = Args::parse();
70949595+ #[cfg(feature = "rocks")]
9696+ if args.print_cursor {
9797+ let storage_dir = args.data.clone().unwrap_or("rocks.test".into());
9898+ let mut store = RocksStorage::open_readonly(storage_dir)?;
9999+ if let Some(cursor) = store.get_cursor()? {
100100+ println!("cursor: {cursor}");
101101+ } else {
102102+ println!("[no cursor]");
103103+ }
104104+ return Ok(());
105105+ }
106106+71107 println!("starting with storage backend: {:?}...", args.backend);
7210873109 let fixture = args.fixture;
110110+ let fixture_preserve_cursor = args.fixture_preserve_cursor;
74111 if let Some(ref p) = fixture {
7575- println!("using fixture at {p:?}...");
112112+ println!("using fixture at {p:?}, preserving cursor? {fixture_preserve_cursor:?}...");
76113 }
7711478115 let stream = jetstream_url(&args.jetstream);
79116 println!("using jetstream server {stream:?}...",);
80117118118+ let bind = args.bind;
119119+ let metrics_bind = args.bind_metrics;
120120+121121+ let collect_metrics = args.collect_metrics;
81122 let stay_alive = CancellationToken::new();
8212383124 match args.backend {
8484- StorageBackend::Memory => run(MemStorage::new(), fixture, None, stream, stay_alive),
125125+ StorageBackend::Memory => run(
126126+ MemStorage::new(),
127127+ fixture,
128128+ fixture_preserve_cursor,
129129+ None,
130130+ args.did_web_domain,
131131+ stream,
132132+ bind,
133133+ metrics_bind,
134134+ collect_metrics,
135135+ stay_alive,
136136+ ),
85137 #[cfg(feature = "rocks")]
86138 StorageBackend::Rocks => {
87139 let storage_dir = args.data.clone().unwrap_or("rocks.test".into());
···96148 rocks.start_backup(backup_dir, auto_backup, stay_alive.clone())?;
97149 }
98150 println!("rocks ready.");
9999- run(rocks, fixture, args.data, stream, stay_alive)
151151+ std::thread::scope(|s| {
152152+ if args.reset_db_start {
153153+ let res = rocks.reset_start();
154154+ eprintln!("reset start finished: {res:?}");
155155+ }
156156+ s.spawn(|| {
157157+ let r = run(
158158+ rocks,
159159+ fixture,
160160+ fixture_preserve_cursor,
161161+ args.data,
162162+ args.did_web_domain,
163163+ stream,
164164+ bind,
165165+ metrics_bind,
166166+ collect_metrics,
167167+ stay_alive,
168168+ );
169169+ eprintln!("run finished: {r:?}");
170170+ r
171171+ });
172172+ });
173173+ Ok(())
100174 }
101175 }
102176}
103177178178+#[allow(clippy::too_many_lines)]
179179+#[allow(clippy::too_many_arguments)]
104180fn run(
105181 mut storage: impl LinkStorage,
106182 fixture: Option<PathBuf>,
183183+ fixture_preserve_cursor: bool,
107184 data_dir: Option<PathBuf>,
185185+ did_web_domain: Option<String>,
108186 stream: String,
187187+ bind: SocketAddr,
188188+ metrics_bind: SocketAddr,
189189+ collect_metrics: bool,
109190 stay_alive: CancellationToken,
110191) -> Result<()> {
111192 ctrlc::set_handler({
···121202 }
122203 })?;
123204205205+ // Install metrics server only if requested
206206+ if collect_metrics {
207207+ install_metrics_server(metrics_bind)?;
208208+ }
209209+124210 let qsize = Arc::new(AtomicU32::new(0));
125211126212 thread::scope(|s| {
···131217 let stay_alive = stay_alive.clone();
132218 let staying_alive = stay_alive.clone();
133219 move || {
134134- if let Err(e) = consume(storage, qsize, fixture, stream, staying_alive) {
220220+ if let Err(e) = consume(
221221+ storage,
222222+ qsize,
223223+ fixture,
224224+ fixture_preserve_cursor,
225225+ stream,
226226+ staying_alive,
227227+ ) {
135228 eprintln!("jetstream finished with error: {e}");
136229 }
137230 stay_alive.drop_guard();
···149242 .enable_all()
150243 .build()
151244 .expect("axum startup")
152152- .block_on(async {
153153- install_metrics_server()?;
154154- serve(readable, "0.0.0.0:6789", staying_alive).await
155155- })
245245+ .block_on(serve(readable, bind, did_web_domain, staying_alive))
156246 .unwrap();
157247 stay_alive.drop_guard();
158248 }
159249 });
160250161161- s.spawn(move || { // monitor thread
162162- let stay_alive = stay_alive.clone();
163163- let check_alive = stay_alive.clone();
251251+ // only spawn monitoring thread if the metrics server is running
252252+ if collect_metrics {
253253+ s.spawn(move || { // monitor thread
254254+ let stay_alive = stay_alive.clone();
255255+ let check_alive = stay_alive.clone();
164256165165- let process_collector = metrics_process::Collector::default();
166166- process_collector.describe();
167167- metrics::describe_gauge!(
168168- "storage_available",
169169- metrics::Unit::Bytes,
170170- "available to be allocated"
171171- );
172172- metrics::describe_gauge!(
173173- "storage_free",
174174- metrics::Unit::Bytes,
175175- "unused bytes in filesystem"
176176- );
177177- if let Some(ref p) = data_dir {
178178- if let Err(e) = fs4::available_space(p) {
179179- eprintln!("fs4 failed to get available space. may not be supported here? space metrics may be absent. e: {e:?}");
180180- } else {
181181- println!("disk space monitoring should work, watching at {p:?}");
182182- }
183183- }
184184-185185- 'monitor: loop {
186186- match readable.get_stats() {
187187- Ok(StorageStats { dids, targetables, linking_records }) => {
188188- metrics::gauge!("storage.stats.dids").set(dids as f64);
189189- metrics::gauge!("storage.stats.targetables").set(targetables as f64);
190190- metrics::gauge!("storage.stats.linking_records").set(linking_records as f64);
257257+ let process_collector = metrics_process::Collector::default();
258258+ if let Some(ref p) = data_dir {
259259+ if let Err(e) = fs4::available_space(p) {
260260+ eprintln!("fs4 failed to get available space. may not be supported here? space metrics may be absent. e: {e:?}");
261261+ } else {
262262+ println!("disk space monitoring should work, watching at {p:?}");
191263 }
192192- Err(e) => eprintln!("failed to get stats: {e:?}"),
193264 }
194265195195- process_collector.collect();
196196- if let Some(ref p) = data_dir {
197197- if let Ok(avail) = fs4::available_space(p) {
198198- metrics::gauge!("storage.available").set(avail as f64);
266266+ 'monitor: loop {
267267+ match readable.get_stats() {
268268+ Ok(StorageStats { dids, targetables, linking_records, .. }) => {
269269+ metrics::gauge!("storage.stats.dids").set(dids as f64);
270270+ metrics::gauge!("storage.stats.targetables").set(targetables as f64);
271271+ metrics::gauge!("storage.stats.linking_records").set(linking_records as f64);
272272+ }
273273+ Err(e) => eprintln!("failed to get stats: {e:?}"),
199274 }
200200- if let Ok(free) = fs4::free_space(p) {
201201- metrics::gauge!("storage.free").set(free as f64);
275275+276276+ process_collector.collect();
277277+ if let Some(ref p) = data_dir {
278278+ if let Ok(avail) = fs4::available_space(p) {
279279+ metrics::gauge!("storage.available").set(avail as f64);
280280+ }
281281+ if let Ok(free) = fs4::free_space(p) {
282282+ metrics::gauge!("storage.free").set(free as f64);
283283+ }
202284 }
203203- }
204204- let wait = time::Instant::now();
205205- while wait.elapsed() < MONITOR_INTERVAL {
206206- thread::sleep(time::Duration::from_millis(100));
207207- if check_alive.is_cancelled() {
208208- break 'monitor
285285+ let wait = time::Instant::now();
286286+ while wait.elapsed() < MONITOR_INTERVAL {
287287+ thread::sleep(time::Duration::from_millis(100));
288288+ if check_alive.is_cancelled() {
289289+ break 'monitor
290290+ }
209291 }
210292 }
211211- }
212212- stay_alive.drop_guard();
213213- });
293293+ stay_alive.drop_guard();
294294+ });
295295+ }
214296 });
215297216298 println!("byeeee");
···218300 Ok(())
219301}
220302221221-fn install_metrics_server() -> Result<()> {
303303+fn install_metrics_server(metrics_bind: SocketAddr) -> Result<()> {
222304 println!("installing metrics server...");
223223- let host = [0, 0, 0, 0];
224224- let port = 8765;
305305+ #[expect(
306306+ deprecated,
307307+ reason = "would change counters to _total suffix, needs dash updates"
308308+ )]
225309 PrometheusBuilder::new()
310310+ .idle_timeout(
311311+ metrics_util::MetricKindMask::ALL,
312312+ Some(time::Duration::from_secs(900)), // 15 min
313313+ )
226314 .set_quantiles(&[0.5, 0.9, 0.99, 1.0])?
227315 .set_bucket_duration(time::Duration::from_secs(30))?
228316 .set_bucket_count(NonZero::new(10).unwrap()) // count * duration = 5 mins. stuff doesn't happen that fast here.
229317 .set_enable_unit_suffix(true)
230230- .with_http_listener((host, port))
318318+ .with_http_listener(metrics_bind)
231319 .install()?;
232232- println!(
233233- "metrics server installed! listening on http://{}.{}.{}.{}:{port}",
234234- host[0], host[1], host[2], host[3]
235235- );
320320+ describe_metrics();
321321+ println!("metrics server installed! listening at {metrics_bind:?}");
236322 Ok(())
323323+}
324324+325325+fn describe_metrics() {
326326+ metrics_process::Collector::default().describe();
327327+ describe_gauge!(
328328+ "storage_available",
329329+ Unit::Bytes,
330330+ "available to be allocated"
331331+ );
332332+ describe_gauge!("storage_free", Unit::Bytes, "unused bytes in filesystem");
333333+ describe_counter!(
334334+ "jetstream_connnect",
335335+ Unit::Count,
336336+ "attempts to connect to a jetstream server"
337337+ );
338338+ describe_counter!(
339339+ "jetstream_read",
340340+ Unit::Count,
341341+ "attempts to read an event from jetstream"
342342+ );
343343+ describe_counter!(
344344+ "jetstream_read_fail",
345345+ Unit::Count,
346346+ "failures to read events from jetstream"
347347+ );
348348+ describe_counter!(
349349+ "jetstream_read_bytes",
350350+ Unit::Bytes,
351351+ "total received message bytes from jetstream"
352352+ );
353353+ describe_counter!(
354354+ "jetstream_read_bytes_decompressed",
355355+ Unit::Bytes,
356356+ "total decompressed message bytes from jetstream"
357357+ );
358358+ describe_histogram!(
359359+ "jetstream_read_bytes_decompressed",
360360+ Unit::Bytes,
361361+ "decompressed size of jetstream messages"
362362+ );
363363+ describe_counter!(
364364+ "jetstream_events",
365365+ Unit::Count,
366366+ "valid json messages received"
367367+ );
368368+ describe_histogram!(
369369+ "jetstream_events_queued",
370370+ Unit::Count,
371371+ "event messages waiting in queue"
372372+ );
373373+ describe_gauge!(
374374+ "jetstream_cursor_age",
375375+ Unit::Microseconds,
376376+ "microseconds between our clock and the jetstream event's time_us"
377377+ );
378378+ describe_counter!(
379379+ "consumer_events_non_actionable",
380380+ Unit::Count,
381381+ "count of non-actionable events"
382382+ );
383383+ describe_counter!(
384384+ "consumer_events_actionable",
385385+ Unit::Count,
386386+ "count of action by type. *all* atproto record delete events are included"
387387+ );
388388+ describe_counter!(
389389+ "consumer_events_actionable_links",
390390+ Unit::Count,
391391+ "total links encountered"
392392+ );
393393+ describe_histogram!(
394394+ "consumer_events_actionable_links",
395395+ Unit::Count,
396396+ "number of links per message"
397397+ );
398398+ #[cfg(feature = "rocks")]
399399+ {
400400+ describe_histogram!(
401401+ "storage_rocksdb_read_seconds",
402402+ Unit::Seconds,
403403+ "duration of the read stage of actions"
404404+ );
405405+ describe_histogram!(
406406+ "storage_rocksdb_action_seconds",
407407+ Unit::Seconds,
408408+ "duration of read + write of actions"
409409+ );
410410+ describe_counter!(
411411+ "storage_rocksdb_batch_ops_total",
412412+ Unit::Count,
413413+ "total batched operations from actions"
414414+ );
415415+ describe_histogram!(
416416+ "storage_rocksdb_delete_account_ops",
417417+ Unit::Count,
418418+ "total batched ops for account deletions"
419419+ );
420420+ }
237421}
238422239423#[cfg(test)]
+239-238
constellation/src/bin/rocks-link-stats.rs
···11-use bincode::config::Options;
22-use clap::Parser;
33-use serde::Serialize;
44-use std::collections::HashMap;
55-use std::path::PathBuf;
11+// use bincode::config::Options;
22+// use clap::Parser;
33+// use serde::Serialize;
44+// use std::collections::HashMap;
55+// use std::path::PathBuf;
6677-use tokio_util::sync::CancellationToken;
77+// use tokio_util::sync::CancellationToken;
8899-use constellation::storage::rocks_store::{
1010- Collection, DidId, RKey, RPath, Target, TargetKey, TargetLinkers, _bincode_opts,
1111-};
1212-use constellation::storage::RocksStorage;
1313-use constellation::Did;
99+// use constellation::storage::rocks_store::{
1010+// Collection, DidId, RKey, RPath, Target, TargetKey, TargetLinkers, _bincode_opts,
1111+// };
1212+// use constellation::storage::RocksStorage;
1313+// use constellation::Did;
14141515-use links::parse_any_link;
1616-use rocksdb::IteratorMode;
1717-use std::time;
1515+// use microcosm_links::parse_any_link;
1616+// use rocksdb::IteratorMode;
1717+// use std::time;
18181919-/// Aggregate links in the at-mosphere
2020-#[derive(Parser, Debug)]
2121-#[command(version, about, long_about = None)]
2222-struct Args {
2323- /// where is rocksdb's data
2424- #[arg(short, long)]
2525- data: PathBuf,
2626- /// slow down so we don't kill the firehose consumer, if running concurrently
2727- #[arg(short, long)]
2828- limit: Option<u64>,
2929-}
1919+// xxxx/// Aggregate links in the at-mosphere
2020+// #[derive(Parser, Debug)]
2121+// #[command(version, about, long_about = None)]
2222+// struct Args {
2323+// /// where is rocksdb's data
2424+// #[arg(short, long)]
2525+// data: PathBuf,
2626+// /// slow down so we don't kill the firehose consumer, if running concurrently
2727+// #[arg(short, long)]
2828+// limit: Option<u64>,
2929+// }
30303131-type LinkType = String;
3131+// type LinkType = String;
32323333-#[derive(Debug, Eq, Hash, PartialEq, Serialize)]
3434-struct SourceLink(Collection, RPath, LinkType, Option<Collection>); // last is target collection, if it's an at-uri link with a collection
3333+// #[derive(Debug, Eq, Hash, PartialEq, Serialize)]
3434+// struct SourceLink(Collection, RPath, LinkType, Option<Collection>); // last is target collection, if it's an at-uri link with a collection
35353636-#[derive(Debug, Serialize)]
3737-struct SourceSample {
3838- did: String,
3939- rkey: String,
4040-}
3636+// #[derive(Debug, Serialize)]
3737+// struct SourceSample {
3838+// did: String,
3939+// rkey: String,
4040+// }
41414242-#[derive(Debug, Default, Serialize)]
4343-struct Bucket {
4444- count: u64,
4545- sum: u64,
4646- sample: Option<SourceSample>,
4747-}
4242+// #[derive(Debug, Default, Serialize)]
4343+// struct Bucket {
4444+// count: u64,
4545+// sum: u64,
4646+// sample: Option<SourceSample>,
4747+// }
48484949-#[derive(Debug, Default, Serialize)]
5050-struct Buckets([Bucket; 23]);
4949+// #[derive(Debug, Default, Serialize)]
5050+// struct Buckets([Bucket; 23]);
51515252-const BUCKETS: [u64; 23] = [
5353- 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 16, 32, 64, 128, 256, 512, 1024, 4096, 16_384, 65_535,
5454- 262_144, 1_048_576,
5555-];
5252+// const BUCKETS: [u64; 23] = [
5353+// 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 16, 32, 64, 128, 256, 512, 1024, 4096, 16_384, 65_535,
5454+// 262_144, 1_048_576,
5555+// ];
56565757-// b1, b2, b3, b4, b5, b6, b7, b8, b9, b10, b12, b16, b32, b64, b128, b256, b512, b1024, b4096, b16384, b65535, b262144, bmax
5757+// xxx// b1, b2, b3, b4, b5, b6, b7, b8, b9, b10, b12, b16, b32, b64, b128, b256, b512, b1024, b4096, b16384, b65535, b262144, bmax
58585959-static DID_IDS_CF: &str = "did_ids";
6060-static TARGET_IDS_CF: &str = "target_ids";
6161-static TARGET_LINKERS_CF: &str = "target_links";
5959+// static DID_IDS_CF: &str = "did_ids";
6060+// static TARGET_IDS_CF: &str = "target_ids";
6161+// static TARGET_LINKERS_CF: &str = "target_links";
62626363-const REPORT_INTERVAL: usize = 50_000;
6363+// const REPORT_INTERVAL: usize = 50_000;
64646565-type Stats = HashMap<SourceLink, Buckets>;
6565+// type Stats = HashMap<SourceLink, Buckets>;
66666767-#[derive(Debug, Serialize)]
6868-struct Printable {
6969- collection: String,
7070- path: String,
7171- link_type: String,
7272- target_collection: Option<String>,
7373- buckets: Buckets,
7474-}
6767+// #[derive(Debug, Serialize)]
6868+// struct Printable {
6969+// collection: String,
7070+// path: String,
7171+// link_type: String,
7272+// target_collection: Option<String>,
7373+// buckets: Buckets,
7474+// }
75757676-#[derive(Debug, Default)]
7777-struct ErrStats {
7878- failed_to_get_sample: usize,
7979- failed_to_read_target_id: usize,
8080- failed_to_deserialize_target_key: usize,
8181- failed_to_parse_target_as_link: usize,
8282- failed_to_get_links: usize,
8383- failed_to_deserialize_linkers: usize,
8484-}
7676+// #[derive(Debug, Default)]
7777+// struct ErrStats {
7878+// failed_to_get_sample: usize,
7979+// failed_to_read_target_id: usize,
8080+// failed_to_deserialize_target_key: usize,
8181+// failed_to_parse_target_as_link: usize,
8282+// failed_to_get_links: usize,
8383+// failed_to_deserialize_linkers: usize,
8484+// }
85858686-fn thousands(n: usize) -> String {
8787- n.to_string()
8888- .as_bytes()
8989- .rchunks(3)
9090- .rev()
9191- .map(std::str::from_utf8)
9292- .collect::<Result<Vec<&str>, _>>()
9393- .unwrap()
9494- .join(",")
9595-}
8686+// fn thousands(n: usize) -> String {
8787+// n.to_string()
8888+// .as_bytes()
8989+// .rchunks(3)
9090+// .rev()
9191+// .map(std::str::from_utf8)
9292+// .collect::<Result<Vec<&str>, _>>()
9393+// .unwrap()
9494+// .join(",")
9595+// }
96969797-fn main() {
9898- let args = Args::parse();
9797+// fn main() {
9898+// let args = Args::parse();
9999100100- let limit = args.limit.map(|amount| {
101101- ratelimit::Ratelimiter::builder(amount, time::Duration::from_secs(1))
102102- .max_tokens(amount)
103103- .initial_available(amount)
104104- .build()
105105- .unwrap()
106106- });
100100+// let limit = args.limit.map(|amount| {
101101+// ratelimit::Ratelimiter::builder(amount, time::Duration::from_secs(1))
102102+// .max_tokens(amount)
103103+// .initial_available(amount)
104104+// .build()
105105+// .unwrap()
106106+// });
107107108108- eprintln!("starting rocksdb...");
109109- let rocks = RocksStorage::open_readonly(args.data).unwrap();
110110- eprintln!("rocks ready.");
108108+// eprintln!("starting rocksdb...");
109109+// let rocks = RocksStorage::open_readonly(args.data).unwrap();
110110+// eprintln!("rocks ready.");
111111112112- let RocksStorage { ref db, .. } = rocks;
112112+// let RocksStorage { ref db, .. } = rocks;
113113114114- let stay_alive = CancellationToken::new();
115115- ctrlc::set_handler({
116116- let mut desperation: u8 = 0;
117117- let stay_alive = stay_alive.clone();
118118- move || match desperation {
119119- 0 => {
120120- eprintln!("ok, shutting down...");
121121- stay_alive.cancel();
122122- desperation += 1;
123123- }
124124- 1.. => panic!("fine, panicking!"),
125125- }
126126- })
127127- .unwrap();
114114+// let stay_alive = CancellationToken::new();
115115+// ctrlc::set_handler({
116116+// let mut desperation: u8 = 0;
117117+// let stay_alive = stay_alive.clone();
118118+// move || match desperation {
119119+// 0 => {
120120+// eprintln!("ok, shutting down...");
121121+// stay_alive.cancel();
122122+// desperation += 1;
123123+// }
124124+// 1.. => panic!("fine, panicking!"),
125125+// }
126126+// })
127127+// .unwrap();
128128129129- let mut stats = Stats::new();
130130- let mut err_stats: ErrStats = Default::default();
129129+// let mut stats = Stats::new();
130130+// let mut err_stats: ErrStats = Default::default();
131131132132- let did_ids_cf = db.cf_handle(DID_IDS_CF).unwrap();
133133- let target_id_cf = db.cf_handle(TARGET_IDS_CF).unwrap();
134134- let target_links_cf = db.cf_handle(TARGET_LINKERS_CF).unwrap();
132132+// let did_ids_cf = db.cf_handle(DID_IDS_CF).unwrap();
133133+// let target_id_cf = db.cf_handle(TARGET_IDS_CF).unwrap();
134134+// let target_links_cf = db.cf_handle(TARGET_LINKERS_CF).unwrap();
135135136136- let t0 = time::Instant::now();
137137- let mut t_prev = t0;
136136+// let t0 = time::Instant::now();
137137+// let mut t_prev = t0;
138138139139- let mut i = 0;
140140- for item in db.iterator_cf(&target_id_cf, IteratorMode::Start) {
141141- if stay_alive.is_cancelled() {
142142- break;
143143- }
139139+// let mut i = 0;
140140+// for item in db.iterator_cf(&target_id_cf, IteratorMode::Start) {
141141+// if stay_alive.is_cancelled() {
142142+// break;
143143+// }
144144145145- if let Some(ref limiter) = limit {
146146- if let Err(dur) = limiter.try_wait() {
147147- std::thread::sleep(dur)
148148- }
149149- }
145145+// if let Some(ref limiter) = limit {
146146+// if let Err(dur) = limiter.try_wait() {
147147+// std::thread::sleep(dur)
148148+// }
149149+// }
150150151151- if i > 0 && i % REPORT_INTERVAL == 0 {
152152- let now = time::Instant::now();
153153- let rate = (REPORT_INTERVAL as f32) / (now.duration_since(t_prev).as_secs_f32());
154154- eprintln!(
155155- "{i}\t({}k)\t{:.2}\t{rate:.1}/s",
156156- thousands(i / 1000),
157157- t0.elapsed().as_secs_f32()
158158- );
159159- t_prev = now;
160160- }
161161- i += 1;
151151+// if i > 0 && i % REPORT_INTERVAL == 0 {
152152+// let now = time::Instant::now();
153153+// let rate = (REPORT_INTERVAL as f32) / (now.duration_since(t_prev).as_secs_f32());
154154+// eprintln!(
155155+// "{i}\t({}k)\t{:.2}\t{rate:.1}/s",
156156+// thousands(i / 1000),
157157+// t0.elapsed().as_secs_f32()
158158+// );
159159+// t_prev = now;
160160+// }
161161+// i += 1;
162162163163- let Ok((target_key, target_id)) = item else {
164164- err_stats.failed_to_read_target_id += 1;
165165- continue;
166166- };
163163+// let Ok((target_key, target_id)) = item else {
164164+// err_stats.failed_to_read_target_id += 1;
165165+// continue;
166166+// };
167167168168- let Ok(TargetKey(Target(target), collection, rpath)) =
169169- _bincode_opts().deserialize(&target_key)
170170- else {
171171- err_stats.failed_to_deserialize_target_key += 1;
172172- continue;
173173- };
168168+// let Ok(TargetKey(Target(target), collection, rpath)) =
169169+// _bincode_opts().deserialize(&target_key)
170170+// else {
171171+// err_stats.failed_to_deserialize_target_key += 1;
172172+// continue;
173173+// };
174174175175- let source = {
176176- let Some(parsed) = parse_any_link(&target) else {
177177- err_stats.failed_to_parse_target_as_link += 1;
178178- continue;
179179- };
180180- SourceLink(
181181- collection,
182182- rpath,
183183- parsed.name().into(),
184184- parsed.at_uri_collection().map(Collection),
185185- )
186186- };
175175+// let source = {
176176+// let Some(parsed) = parse_any_link(&target) else {
177177+// err_stats.failed_to_parse_target_as_link += 1;
178178+// continue;
179179+// };
180180+// SourceLink(
181181+// collection,
182182+// rpath,
183183+// parsed.name().into(),
184184+// parsed.at_uri_collection().map(Collection),
185185+// )
186186+// };
187187188188- let Ok(Some(links_raw)) = db.get_cf(&target_links_cf, &target_id) else {
189189- err_stats.failed_to_get_links += 1;
190190- continue;
191191- };
192192- let Ok(linkers) = _bincode_opts().deserialize::<TargetLinkers>(&links_raw) else {
193193- err_stats.failed_to_deserialize_linkers += 1;
194194- continue;
195195- };
196196- let (n, _) = linkers.count();
188188+// let Ok(Some(links_raw)) = db.get_cf(&target_links_cf, &target_id) else {
189189+// err_stats.failed_to_get_links += 1;
190190+// continue;
191191+// };
192192+// let Ok(linkers) = _bincode_opts().deserialize::<TargetLinkers>(&links_raw) else {
193193+// err_stats.failed_to_deserialize_linkers += 1;
194194+// continue;
195195+// };
196196+// let (n, _) = linkers.count();
197197198198- if n == 0 {
199199- continue;
200200- }
198198+// if n == 0 {
199199+// continue;
200200+// }
201201202202- let mut bucket = 0;
203203- for edge in BUCKETS {
204204- if n <= edge || bucket == 22 {
205205- break;
206206- }
207207- bucket += 1;
208208- }
202202+// let mut bucket = 0;
203203+// for edge in BUCKETS {
204204+// if n <= edge || bucket == 22 {
205205+// break;
206206+// }
207207+// bucket += 1;
208208+// }
209209210210- let b = &mut stats.entry(source).or_default().0[bucket];
211211- b.count += 1;
212212- b.sum += n;
213213- if b.sample.is_none() {
214214- let (DidId(did_id), RKey(k)) = &linkers.0[(n - 1) as usize];
215215- if let Ok(Some(did_bytes)) = db.get_cf(&did_ids_cf, did_id.to_be_bytes()) {
216216- if let Ok(Did(did)) = _bincode_opts().deserialize(&did_bytes) {
217217- b.sample = Some(SourceSample {
218218- did,
219219- rkey: k.clone(),
220220- });
221221- } else {
222222- err_stats.failed_to_get_sample += 1;
223223- }
224224- } else {
225225- err_stats.failed_to_get_sample += 1;
226226- }
227227- }
210210+// let b = &mut stats.entry(source).or_default().0[bucket];
211211+// b.count += 1;
212212+// b.sum += n;
213213+// if b.sample.is_none() {
214214+// let (DidId(did_id), RKey(k)) = &linkers.0[(n - 1) as usize];
215215+// if let Ok(Some(did_bytes)) = db.get_cf(&did_ids_cf, did_id.to_be_bytes()) {
216216+// if let Ok(Did(did)) = _bincode_opts().deserialize(&did_bytes) {
217217+// b.sample = Some(SourceSample {
218218+// did,
219219+// rkey: k.clone(),
220220+// });
221221+// } else {
222222+// err_stats.failed_to_get_sample += 1;
223223+// }
224224+// } else {
225225+// err_stats.failed_to_get_sample += 1;
226226+// }
227227+// }
228228229229- // if i >= 40_000 {
230230- // break;
231231- // }
232232- }
229229+// // if i >= 40_000 {
230230+// // break;
231231+// // }
232232+// }
233233234234- let dt = t0.elapsed();
234234+// let dt = t0.elapsed();
235235236236- eprintln!("gathering stats for output...");
236236+// eprintln!("gathering stats for output...");
237237238238- let itemified = stats
239239- .into_iter()
240240- .map(
241241- |(
242242- SourceLink(Collection(collection), RPath(path), link_type, target_collection),
243243- buckets,
244244- )| Printable {
245245- collection,
246246- path,
247247- link_type,
248248- target_collection: target_collection.map(|Collection(c)| c),
249249- buckets,
250250- },
251251- )
252252- .collect::<Vec<_>>();
238238+// let itemified = stats
239239+// .into_iter()
240240+// .map(
241241+// |(
242242+// SourceLink(Collection(collection), RPath(path), link_type, target_collection),
243243+// buckets,
244244+// )| Printable {
245245+// collection,
246246+// path,
247247+// link_type,
248248+// target_collection: target_collection.map(|Collection(c)| c),
249249+// buckets,
250250+// },
251251+// )
252252+// .collect::<Vec<_>>();
253253254254- match serde_json::to_string(&itemified) {
255255- Ok(s) => println!("{s}"),
256256- Err(e) => eprintln!("failed to serialize results: {e:?}"),
257257- }
254254+// match serde_json::to_string(&itemified) {
255255+// Ok(s) => println!("{s}"),
256256+// Err(e) => eprintln!("failed to serialize results: {e:?}"),
257257+// }
258258259259- eprintln!(
260260- "{} summarizing {} link targets in {:.1}s",
261261- if stay_alive.is_cancelled() {
262262- "STOPPED"
263263- } else {
264264- "FINISHED"
265265- },
266266- thousands(i),
267267- dt.as_secs_f32()
268268- );
269269- eprintln!("{err_stats:?}");
270270- eprintln!("bye.");
271271-}
259259+// eprintln!(
260260+// "{} summarizing {} link targets in {:.1}s",
261261+// if stay_alive.is_cancelled() {
262262+// "STOPPED"
263263+// } else {
264264+// "FINISHED"
265265+// },
266266+// thousands(i),
267267+// dt.as_secs_f32()
268268+// );
269269+// eprintln!("{err_stats:?}");
270270+// eprintln!("bye.");
271271+// }
272272273273-// scan plan
273273+// xxx// scan plan
274274275275-// buckets (backlink count)
276276-// 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 16, 32, 64, 128, 256, 512, 1024, 4096, 16384, 65535, 262144, 1048576+
277277-// by
278278-// - collection
279279-// - json path
280280-// - link type
281281-// samples for each bucket for each variation
275275+// xxx// buckets (backlink count)
276276+// xxx// 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 16, 32, 64, 128, 256, 512, 1024, 4096, 16384, 65535, 262144, 1048576+
277277+// xxx// by
278278+// xxx// - collection
279279+// xxx// - json path
280280+// xxx// - link type
281281+// xxx// samples for each bucket for each variation
282282+fn main() {}
···11+{% extends "base.html.j2" %}
22+{% import "try-it-macros.html.j2" as try_it %}
33+44+{% block title %}Many to Many counts{% endblock %}
55+{% block description %}Counts of many-to-many {{ query.source }} join records with links to {{ query.subject }} and a secondary target at {{ query.path_to_other }}{% endblock %}
66+77+{% block content %}
88+99+ {% call try_it::get_many_to_many_counts(
1010+ query.subject,
1111+ query.source,
1212+ query.path_to_other,
1313+ query.did,
1414+ query.other_subject,
1515+ query.limit,
1616+ ) %}
1717+1818+ <h2>
1919+ Many-to-many links to <code>{{ query.subject }}</code> joining through <code>{{ query.path_to_other }}</code>
2020+ {% if let Some(browseable_uri) = query.subject|to_browseable %}
2121+ <small style="font-weight: normal; font-size: 1rem"><a href="{{ browseable_uri }}">browse record</a></small>
2222+ {% endif %}
2323+ </h2>
2424+2525+ <p><strong>{% if cursor.is_some() || query.cursor.is_some() %}more than {% endif %}{{ counts_by_other_subject.len()|to_u64|human_number }} joins</strong> <code>{{ query.source }}→{{ query.path_to_other }}</code></p>
2626+2727+ <ul>
2828+ <li>See direct backlinks at <code>/xrpc/blue.microcosm.links.getBacklinks</code>: <a href="/xrpc/blue.microcosm.links.getBacklinks?subject={{ query.subject|urlencode }}&source={{ query.source|urlencode }}">/xrpc/blue.microcosm.links.getBacklinks?subject={{ query.subject }}&source={{ query.source }}</a></li>
2929+ <li>See all links to this target at <code>/links/all</code>: <a href="/links/all?target={{ query.subject|urlencode }}">/links/all?target={{ query.subject }}</a></li>
3030+ </ul>
3131+3232+ <h3>Counts by other subject:</h3>
3333+3434+ {% for counts in counts_by_other_subject %}
3535+ <pre style="display: block; margin: 1em 2em" class="code"><strong>Joined subject</strong>: {{ counts.subject }}
3636+<strong>Joining records</strong>: {{ counts.total }}
3737+<strong>Unique joiner ids</strong>: {{ counts.distinct }}
3838+-> {% if let Some(browseable_uri) = counts.subject|to_browseable -%}
3939+ <a href="{{ browseable_uri }}">browse record</a>
4040+ {%- endif %}</pre>
4141+ {% endfor %}
4242+4343+ {% if let Some(c) = cursor %}
4444+ <form method="get" action="/xrpc/blue.microcosm.links.getManyToManyCounts">
4545+ <input type="hidden" name="subject" value="{{ query.subject }}" />
4646+ <input type="hidden" name="source" value="{{ query.source }}" />
4747+ <input type="hidden" name="pathToOther" value="{{ query.path_to_other }}" />
4848+ {% for did in query.did %}
4949+ <input type="hidden" name="did" value="{{ did }}" />
5050+ {% endfor %}
5151+ {% for otherSubject in query.other_subject %}
5252+ <input type="hidden" name="otherSubject" value="{{ otherSubject }}" />
5353+ {% endfor %}
5454+ <input type="hidden" name="limit" value="{{ query.limit }}" />
5555+ <input type="hidden" name="cursor" value={{ c|json|safe }} />
5656+ <button type="submit">next page…</button>
5757+ </form>
5858+ {% else %}
5959+ <button disabled><em>end of results</em></button>
6060+ {% endif %}
6161+6262+ <details>
6363+ <summary>Raw JSON response</summary>
6464+ <pre class="code">{{ self|tojson }}</pre>
6565+ </details>
6666+6767+{% endblock %}
+64
constellation/templates/get-many-to-many.html.j2
···11+{% extends "base.html.j2" %}
22+{% import "try-it-macros.html.j2" as try_it %}
33+44+{% block title %}Many-to-Many Links{% endblock %}
55+{% block description %}All {{ query.source }} records with many-to-many links to {{ query.subject }} joining through {{ query.path_to_other }}{% endblock %}
66+77+{% block content %}
88+99+ {% call try_it::get_many_to_many(query.subject, query.source, query.path_to_other, query.link_did, query.other_subject, query.limit) %}
1010+1111+ <h2>
1212+ Many-to-many links to <code>{{ query.subject }}</code>
1313+ {% if let Some(browseable_uri) = query.subject|to_browseable %}
1414+ <small style="font-weight: normal; font-size: 1rem"><a href="{{ browseable_uri }}">browse record</a></small>
1515+ {% endif %}
1616+ </h2>
1717+1818+ <p><strong>Many-to-many links</strong> from <code>{{ query.source }}</code> joining through <code>{{ query.path_to_other }}</code></p>
1919+2020+ <ul>
2121+ <li>See all links to this target at <code>/links/all</code>: <a href="/links/all?target={{ query.subject|urlencode }}">/links/all?target={{ query.subject }}</a></li>
2222+ {# todo: add link to see many-to-many counts #}
2323+ </ul>
2424+2525+ <h3>Many-to-many links, most recent first:</h3>
2626+2727+ {% for item in items %}
2828+<pre style="display: block; margin: 1em 2em" class="code"><strong>Linking record</strong>:
2929+ {%- if let Some(uri) = item.link_record.uri().as_str()|to_browseable %} <a href="{{ uri }}">browse link record</a>{% endif %}
3030+ DID: {{ item.link_record.did().0 }}
3131+ Collection: {{ item.link_record.collection() }}
3232+ RKey: {{ item.link_record.rkey() }}
3333+<strong>Other subject</strong>: {{ item.other_subject }}
3434+ {%- if let Some(uri) = item.other_subject.as_str()|to_browseable %}
3535+ -> <a href="{{ uri }}">browse subject</a>
3636+ {%- endif %}
3737+</pre>
3838+ {% endfor %}
3939+4040+ {% if let Some(c) = cursor %}
4141+ <form method="get" action="/xrpc/blue.microcosm.links.getManyToMany">
4242+ <input type="hidden" name="subject" value="{{ query.subject }}" />
4343+ <input type="hidden" name="source" value="{{ query.source }}" />
4444+ <input type="hidden" name="pathToOther" value="{{ query.path_to_other }}" />
4545+ {% for did in query.link_did %}
4646+ <input type="hidden" name="did" value="{{ did }}" />
4747+ {% endfor %}
4848+ {% for other in query.other_subject %}
4949+ <input type="hidden" name="otherSubject" value="{{ other }}" />
5050+ {% endfor %}
5151+ <input type="hidden" name="limit" value="{{ query.limit }}" />
5252+ <input type="hidden" name="cursor" value={{ c|json|safe }} />
5353+ <button type="submit">next page…</button>
5454+ </form>
5555+ {% else %}
5656+ <button disabled><em>end of results</em></button>
5757+ {% endif %}
5858+5959+ <details>
6060+ <summary>Raw JSON response</summary>
6161+ <pre class="code">{{ self|tojson }}</pre>
6262+ </details>
6363+6464+{% endblock %}
+129-10
constellation/templates/hello.html.j2
···1919 <p>It works by recursively walking <em>all</em> records coming through the firehose, searching for anything that looks like a link. Links are indexed by the target they point at, the collection the record came from, and the JSON path to the link in that record.</p>
20202121 <p>
2222- This server has indexed <span class="stat">{{ stats.linking_records|human_number }}</span> links between <span class="stat">{{ stats.targetables|human_number }}</span> targets and sources from <span class="stat">{{ stats.dids|human_number }}</span> identities over <span class="stat">{{ days_indexed|human_number }}</span> days.<br/>
2323- <small>(indexing new records in real time, backfill still TODO)</small>
2222+ This server has indexed <span class="stat">{{ stats.linking_records|human_number }}</span> links between <span class="stat">{{ stats.targetables|human_number }}</span> targets and sources from <span class="stat">{{ stats.dids|human_number }}</span> identities over <span class="stat">
2323+ {%- if let Some(days) = days_indexed %}
2424+ {{ days|human_number }}
2525+ {% else %}
2626+ ???
2727+ {% endif -%}
2828+ </span> days.<br/>
2929+ <small>(indexing new records in real time, backfill coming soon!)</small>
2430 </p>
25312626- <p>The API is currently <strong>unstable</strong>. But feel free to use it! If you want to be nice, put your project name and bsky username (or email) in your user-agent header for api requests.</p>
3232+ {# {% for k, v in stats.other_data.iter() %}
3333+ <p><strong>{{ k }}</strong>: {{ v }}</p>
3434+ {% endfor %} #}
3535+3636+ <p>You're welcome to use this public instance! Please do not build the torment nexus. If you want to be nice, put your project name and bsky username (or email) in your user-agent header for api requests.</p>
273728382939 <h2>API Endpoints</h2>
30404141+ <h3 class="route"><code>GET /xrpc/blue.microcosm.links.getBacklinks</code></h3>
4242+4343+ <p>A list of records linking to any record, identity, or uri.</p>
4444+4545+ <h4>Query parameters:</h4>
4646+4747+ <ul>
4848+ <li><p><code>subject</code>: required, must url-encode. Example: <code>at://did:plc:vc7f4oafdgxsihk4cry2xpze/app.bsky.feed.post/3lgwdn7vd722r</code></p></li>
4949+ <li><p><code>source</code>: required. Example: <code>app.bsky.feed.like:subject.uri</code></p></li>
5050+ <li><p><code>did</code>: optional, filter links to those from specific users. Include multiple times to filter by multiple users. Example: <code>did=did:plc:vc7f4oafdgxsihk4cry2xpze&did=did:plc:vc7f4oafdgxsihk4cry2xpze</code></p></li>
5151+ <li><p><code>limit</code>: optional. Default: <code>16</code>. Maximum: <code>100</code></p></li>
5252+ <li><p><code>reverse</code>: optional, return links in reverse order. Default: <code>false</code></p></li>
5353+ </ul>
5454+5555+ <p style="margin-bottom: 0"><strong>Try it:</strong></p>
5656+ {% call
5757+ try_it::get_backlinks("at://did:plc:a4pqq234yw7fqbddawjo7y35/app.bsky.feed.post/3m237ilwc372e", "app.bsky.feed.like:subject.uri", [""], 16, false) %}
5858+5959+6060+ <h3 class="route"><code>GET /xrpc/blue.microcosm.links.getManyToManyCounts</code></h3>
6161+6262+ <p>TODO: description</p>
6363+6464+ <h4>Query parameters:</h4>
6565+6666+ <ul>
6767+ <li><p><code>subject</code>: required, must url-encode. Example: <code>at://did:plc:vc7f4oafdgxsihk4cry2xpze/app.bsky.feed.post/3lgwdn7vd722r</code></p></li>
6868+ <li><p><code>source</code>: required. Example: <code>app.bsky.feed.like:subject.uri</code></p></li>
6969+ <li><p><code>pathToOther</code>: required. Path to the secondary link in the many-to-many record. Example: <code>otherThing.uri</code></p></li>
7070+ <li><p><code>did</code>: optional, filter links to those from specific users. Include multiple times to filter by multiple users. Example: <code>did=did:plc:vc7f4oafdgxsihk4cry2xpze&did=did:plc:vc7f4oafdgxsihk4cry2xpze</code></p></li>
7171+ <li><p><code>otherSubject</code>: optional, filter secondary links to specific subjects. Include multiple times to filter by multiple users. Example: <code>at://did:plc:vc7f4oafdgxsihk4cry2xpze/app.bsky.feed.post/3lgwdn7vd722r</code></p></li>
7272+ <li><p><code>limit</code>: optional. Default: <code>16</code>. Maximum: <code>100</code></p></li>
7373+ </ul>
7474+7575+ <p style="margin-bottom: 0"><strong>Try it:</strong></p>
7676+ {% call try_it::get_many_to_many_counts(
7777+ "at://did:plc:wshs7t2adsemcrrd4snkeqli/sh.tangled.label.definition/good-first-issue",
7878+ "sh.tangled.label.op:add[].key",
7979+ "subject",
8080+ [""],
8181+ [""],
8282+ 25,
8383+ ) %}
8484+8585+ <h3 class="route"><code>GET /xrpc/blue.microcosm.links.getManyToMany</code></h3>
8686+8787+ <p>A list of many-to-many join records linking to a target and a secondary target.</p>
8888+8989+ <h4>Query parameters:</h4>
9090+9191+ <ul>
9292+ <li><p><code>subject</code>: required, must url-encode. Example: <code>at://did:plc:vc7f4oafdgxsihk4cry2xpze/app.bsky.feed.post/3lgwdn7vd722r</code></p></li>
9393+ <li><p><code>source</code>: required. Example: <code>app.bsky.feed.like:subject.uri</code></p></li>
9494+ <li><p><code>pathToOther</code>: required. Path to the secondary link in the many-to-many record. Example: <code>otherThing.uri</code></p></li>
9595+ <li><p><code>did</code>: optional, filter links to those from specific users. Include multiple times to filter by multiple users. Example: <code>did=did:plc:vc7f4oafdgxsihk4cry2xpze&did=did:plc:vc7f4oafdgxsihk4cry2xpze</code></p></li>
9696+ <li><p><code>otherSubject</code>: optional, filter secondary links to specific subjects. Include multiple times to filter by multiple subjects. Example: <code>at://did:plc:vc7f4oafdgxsihk4cry2xpze/app.bsky.feed.post/3lgwdn7vd722r</code></p></li>
9797+ <li><p><code>limit</code>: optional. Default: <code>16</code>. Maximum: <code>100</code></p></li>
9898+ </ul>
9999+100100+ <p style="margin-bottom: 0"><strong>Try it:</strong></p>
101101+ {% call try_it::get_many_to_many(
102102+ "at://did:plc:uyauirpjzk6le4ygqzatcwnq/app.bsky.graph.list/3lzhg33t5bf2h",
103103+ "app.bsky.graph.listitem:list",
104104+ "subject",
105105+ [""],
106106+ [""],
107107+ 16,
108108+ ) %}
109109+110110+ <h3 class="route"><code>GET /xrpc/blue.microcosm.links.getDistinct</code></h3>
111111+112112+ <p>A list of distinct DIDs (identities) with links to a target.</p>
113113+114114+ <h4>Query parameters:</h4>
115115+116116+ <ul>
117117+ <li><code>subject</code>: required, must url-encode. The target being linked to. Example: <code>did:plc:vc7f4oafdgxsihk4cry2xpze</code> or <code>at://did:plc:vc7f4oafdgxsihk4cry2xpze/app.bsky.feed.post/3lgwdn7vd722r</code></li>
118118+ <li><code>source</code>: required. Collection and path specification for the primary link. Example: <code>app.bsky.feed.like:subject.uri</code></li>
119119+ <li><code>limit</code>: optional. Number of results to return. Default: <code>16</code>. Maximum: <code>100</code></li>
120120+ <li><code>cursor</code>: optional, see Definitions.</li>
121121+ </ul>
122122+123123+ <p style="margin-bottom: 0"><strong>Try it:</strong></p>
124124+ {% call try_it::get_backlink_dids("at://did:plc:vc7f4oafdgxsihk4cry2xpze/app.bsky.feed.post/3lgwdn7vd722r", "app.bsky.feed.like:subject.uri") %}
125125+31126 <h3 class="route"><code>GET /links</code></h3>
3212733128 <p>A list of records linking to a target.</p>
34129130130+ <p>[DEPRECATED]: use <code>GET /xrpc/blue.microcosm.links.getBacklinks</code>. New apps should avoid it, but this endpoint <strong>will</strong> remain supported for the forseeable future.</p>
131131+35132 <h4>Query parameters:</h4>
3613337134 <ul>
3838- <li><code>target</code>: required, must url-encode. Example: <code>at://did:plc:vc7f4oafdgxsihk4cry2xpze/app.bsky.feed.post/3lgwdn7vd722r</code></li>
3939- <li><code>collection</code>: required. Example: <code>app.bsky.feed.like</code></li>
4040- <li><code>path</code>: required, must url-encode. Example: <code>.subject.uri</code></li>
135135+ <li><p><code>target</code>: required, must url-encode. Example: <code>at://did:plc:vc7f4oafdgxsihk4cry2xpze/app.bsky.feed.post/3lgwdn7vd722r</code></p></li>
136136+ <li><p><code>collection</code>: required. Example: <code>app.bsky.feed.like</code></p></li>
137137+ <li><p><code>path</code>: required, must url-encode. Example: <code>.subject.uri</code></p></li>
138138+ <li><p><code>did</code>: optional, filter links to those from specific users. Include multiple times to filter by multiple users. Example: <code>did=did:plc:vc7f4oafdgxsihk4cry2xpze&did=did:plc:vc7f4oafdgxsihk4cry2xpze</code></p></li>
139139+ <li><p><code>from_dids</code> [deprecated]: optional. Use <code>did</code> instead. Example: <code>from_dids=did:plc:vc7f4oafdgxsihk4cry2xpze,did:plc:vc7f4oafdgxsihk4cry2xpze</code></p></li>
140140+ <li><p><code>limit</code>: optional. Default: <code>16</code>. Maximum: <code>100</code></p></li>
141141+ <li><p><code>reverse</code>: optional, return links in reverse order. Default: <code>false</code></p></li>
41142 </ul>
4214343144 <p style="margin-bottom: 0"><strong>Try it:</strong></p>
4444- {% call try_it::links("at://did:plc:vc7f4oafdgxsihk4cry2xpze/app.bsky.feed.post/3lgwdn7vd722r", "app.bsky.feed.like", ".subject.uri") %}
4545-145145+ {% call try_it::links("at://did:plc:a4pqq234yw7fqbddawjo7y35/app.bsky.feed.post/3m237ilwc372e", "app.bsky.feed.like", ".subject.uri", [""], 16) %}
4614647147 <h3 class="route"><code>GET /links/distinct-dids</code></h3>
48148···60160 {% call try_it::dids("at://did:plc:vc7f4oafdgxsihk4cry2xpze/app.bsky.feed.post/3lgwdn7vd722r", "app.bsky.feed.like", ".subject.uri") %}
61161621626363- <h3 class="route"><code>GET /links/count</code></h3>
163163+ <h3 class="route deprecated"><code>[deprecated] GET /links/count</code></h3>
6416465165 <p>The total number of links pointing at a given target.</p>
66166···76176 <p style="margin-bottom: 0"><strong>Try it:</strong></p>
77177 {% call try_it::links_count("did:plc:vc7f4oafdgxsihk4cry2xpze", "app.bsky.graph.block", ".subject") %}
78178179179+ <h3 class="route"><code>GET /xrpc/blue.microcosm.links.getBacklinksCount</code></h3>
180180+181181+ <p>The total number of links pointing at a given target.</p>
182182+183183+ <h4>Query parameters:</h4>
184184+185185+ <ul>
186186+ <li><code>subject</code>: required, must url-encode. The target being linked to. Example: <code>did:plc:vc7f4oafdgxsihk4cry2xpze</code> or <code>at://did:plc:vc7f4oafdgxsihk4cry2xpze/app.bsky.feed.post/3lgwdn7vd722r</code></li>
187187+ <li><code>source</code>: required. Collection and path specification for the primary link. Example: <code>app.bsky.feed.like:subject.uri</code></li>
188188+ </ul>
189189+190190+ <p style="margin-bottom: 0"><strong>Try it:</strong></p>
191191+ {% call try_it::get_backlinks_count("did:plc:vc7f4oafdgxsihk4cry2xpze", "app.bsky.graph.block:subject") %}
7919280193 <h3 class="route"><code>GET /links/count/distinct-dids</code></h3>
81194···130243131244 <p>A DID like <code>did:plc:hdhoaan3xa3jiuq4fg4mefid</code>, or an AT-URI like <code>at://did:plc:z72i7hdynmk6r22z27h6tvur/app.bsky.feed.post/3lgu4lg6j2k2v</code>, or a URI like <code>https://example.com</code>.</p>
132245246246+ <h3>Source</h3>
247247+248248+ <p>A <em>link source</em>, made of a collection and path, like <code>app.bsky.feed.like:subject<code>. The <code>:</code> separates them.
249249+133250 <h3>Collection</h3>
134251135252 <p>A record NSID like <code>app.bsky.feed.like</code>.</p>
136253137254 <h3>Path</h3>
138255139139- <p>A (currently-very-very-hacky) json-path-ish representation of the source of a link in a record. Records may contain multiple links with different meanings, so this specifies which specific link is of interest. Like <code>.subject.uri</code>.</p>
256256+ <p>A (currently-hacky) json-path-ish representation of the source of a link in a record. Records may contain multiple links with different meanings, so this specifies which specific link is of interest. Like <code>.subject.uri</code>.</p>
257257+258258+ <p>A special path, <code>.</code>, represents <em>the record's <code>rkey</code></em>. Tangled's vouch system puts the vouch subject in the <code>rkey</code> instead of inside the actual record. Its link source looks like this: <code>sh.tangled.graph.vouch:.</code></p>
140259141260 <h3>Cursor</h3>
142261
···11+# reflector
22+33+a tiny did:web service server that maps subdomains to a single service endpoint
44+55+receiving requests from multiple subdomains is left as a problem for the reverse proxy to solve, since acme wildcard certificates (ie. letsencrypt) require the most complicated and involved challenge type (DNS).
66+77+caddy [has good support for](https://caddyserver.com/docs/caddyfile/patterns#wildcard-certificates) configuring the wildcard DNS challenge with various DNS providers, and also supports [on-demand](https://caddyserver.com/docs/automatic-https#using-on-demand-tls) provisioning via the simpler methods.
88+99+if you only need a small fixed number of subdomains, you can also use certbot or otherwise individually configure them in your reverse proxy.
1010+1111+1212+## license
1313+1414+This work is dual-licensed under MIT and Apache 2.0. You can choose between one of them if you use this work.
1515+1616+`SPDX-License-Identifier: MIT OR Apache-2.0`
+112
legacy/reflector/src/main.rs
···11+use clap::Parser;
22+use poem::{
33+ EndpointExt, Response, Route, Server, get, handler,
44+ http::StatusCode,
55+ listener::TcpListener,
66+ middleware::{AddData, Tracing},
77+ web::{Data, Json, Query, TypedHeader, headers::Host},
88+};
99+use serde::{Deserialize, Serialize};
1010+1111+#[handler]
1212+fn hello() -> String {
1313+ "ɹoʇɔǝʅⅎǝɹ".to_string()
1414+}
1515+1616+#[derive(Debug, Serialize)]
1717+struct DidDoc {
1818+ id: String,
1919+ service: [DidService; 1],
2020+}
2121+2222+#[derive(Debug, Clone, Serialize)]
2323+#[serde(rename_all = "camelCase")]
2424+struct DidService {
2525+ id: String,
2626+ r#type: String,
2727+ service_endpoint: String,
2828+}
2929+3030+#[handler]
3131+fn did_doc(TypedHeader(host): TypedHeader<Host>, service: Data<&DidService>) -> Json<DidDoc> {
3232+ Json(DidDoc {
3333+ id: format!("did:web:{}", host.hostname()),
3434+ service: [service.clone()],
3535+ })
3636+}
3737+3838+#[derive(Deserialize)]
3939+struct AskQuery {
4040+ domain: String,
4141+}
4242+#[handler]
4343+fn ask_caddy(
4444+ Data(parent): Data<&Option<String>>,
4545+ Query(AskQuery { domain }): Query<AskQuery>,
4646+) -> Response {
4747+ if let Some(parent) = parent
4848+ && let Some(prefix) = domain.strip_suffix(&format!(".{parent}"))
4949+ && !prefix.contains('.')
5050+ {
5151+ // no sub-sub-domains allowed
5252+ return Response::builder().body("ok");
5353+ };
5454+ Response::builder()
5555+ .status(StatusCode::FORBIDDEN)
5656+ .body("nope")
5757+}
5858+5959+/// Slingshot record edge cache
6060+#[derive(Parser, Debug, Clone)]
6161+#[command(version, about, long_about = None)]
6262+struct Args {
6363+ /// The DID document service ID to serve
6464+ ///
6565+ /// must start with a '#', like `#bsky_appview'
6666+ #[arg(long)]
6767+ id: String,
6868+ /// Service type
6969+ ///
7070+ /// Not sure exactly what its requirements are. 'BlueskyAppview' for example
7171+ #[arg(long)]
7272+ r#type: String,
7373+ /// The HTTPS endpoint for the service
7474+ #[arg(long)]
7575+ service_endpoint: String,
7676+ /// The parent domain; requests should come from subdomains of this
7777+ #[arg(long)]
7878+ domain: Option<String>,
7979+}
8080+8181+impl From<Args> for DidService {
8282+ fn from(a: Args) -> Self {
8383+ Self {
8484+ id: a.id,
8585+ r#type: a.r#type,
8686+ service_endpoint: a.service_endpoint,
8787+ }
8888+ }
8989+}
9090+9191+#[tokio::main(flavor = "current_thread")]
9292+async fn main() {
9393+ tracing_subscriber::fmt::init();
9494+ log::info!("ɹoʇɔǝʅⅎǝɹ");
9595+9696+ let args = Args::parse();
9797+ let domain = args.domain.clone();
9898+ let service: DidService = args.into();
9999+100100+ Server::new(TcpListener::bind("0.0.0.0:3001"))
101101+ .run(
102102+ Route::new()
103103+ .at("/", get(hello))
104104+ .at("/.well-known/did.json", get(did_doc))
105105+ .at("/ask", get(ask_caddy))
106106+ .with(AddData::new(service))
107107+ .with(AddData::new(domain))
108108+ .with(Tracing),
109109+ )
110110+ .await
111111+ .unwrap()
112112+}
···11+ Apache License
22+ Version 2.0, January 2004
33+ http://www.apache.org/licenses/
44+55+TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
66+77+1. Definitions.
88+99+ "License" shall mean the terms and conditions for use, reproduction,
1010+ and distribution as defined by Sections 1 through 9 of this document.
1111+1212+ "Licensor" shall mean the copyright owner or entity authorized by
1313+ the copyright owner that is granting the License.
1414+1515+ "Legal Entity" shall mean the union of the acting entity and all
1616+ other entities that control, are controlled by, or are under common
1717+ control with that entity. For the purposes of this definition,
1818+ "control" means (i) the power, direct or indirect, to cause the
1919+ direction or management of such entity, whether by contract or
2020+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
2121+ outstanding shares, or (iii) beneficial ownership of such entity.
2222+2323+ "You" (or "Your") shall mean an individual or Legal Entity
2424+ exercising permissions granted by this License.
2525+2626+ "Source" form shall mean the preferred form for making modifications,
2727+ including but not limited to software source code, documentation
2828+ source, and configuration files.
2929+3030+ "Object" form shall mean any form resulting from mechanical
3131+ transformation or translation of a Source form, including but
3232+ not limited to compiled object code, generated documentation,
3333+ and conversions to other media types.
3434+3535+ "Work" shall mean the work of authorship, whether in Source or
3636+ Object form, made available under the License, as indicated by a
3737+ copyright notice that is included in or attached to the work
3838+ (an example is provided in the Appendix below).
3939+4040+ "Derivative Works" shall mean any work, whether in Source or Object
4141+ form, that is based on (or derived from) the Work and for which the
4242+ editorial revisions, annotations, elaborations, or other modifications
4343+ represent, as a whole, an original work of authorship. For the purposes
4444+ of this License, Derivative Works shall not include works that remain
4545+ separable from, or merely link (or bind by name) to the interfaces of,
4646+ the Work and Derivative Works thereof.
4747+4848+ "Contribution" shall mean any work of authorship, including
4949+ the original version of the Work and any modifications or additions
5050+ to that Work or Derivative Works thereof, that is intentionally
5151+ submitted to Licensor for inclusion in the Work by the copyright owner
5252+ or by an individual or Legal Entity authorized to submit on behalf of
5353+ the copyright owner. For the purposes of this definition, "submitted"
5454+ means any form of electronic, verbal, or written communication sent
5555+ to the Licensor or its representatives, including but not limited to
5656+ communication on electronic mailing lists, source code control systems,
5757+ and issue tracking systems that are managed by, or on behalf of, the
5858+ Licensor for the purpose of discussing and improving the Work, but
5959+ excluding communication that is conspicuously marked or otherwise
6060+ designated in writing by the copyright owner as "Not a Contribution."
6161+6262+ "Contributor" shall mean Licensor and any individual or Legal Entity
6363+ on behalf of whom a Contribution has been received by Licensor and
6464+ subsequently incorporated within the Work.
6565+6666+2. Grant of Copyright License. Subject to the terms and conditions of
6767+ this License, each Contributor hereby grants to You a perpetual,
6868+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
6969+ copyright license to reproduce, prepare Derivative Works of,
7070+ publicly display, publicly perform, sublicense, and distribute the
7171+ Work and such Derivative Works in Source or Object form.
7272+7373+3. Grant of Patent License. Subject to the terms and conditions of
7474+ this License, each Contributor hereby grants to You a perpetual,
7575+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
7676+ (except as stated in this section) patent license to make, have made,
7777+ use, offer to sell, sell, import, and otherwise transfer the Work,
7878+ where such license applies only to those patent claims licensable
7979+ by such Contributor that are necessarily infringed by their
8080+ Contribution(s) alone or by combination of their Contribution(s)
8181+ with the Work to which such Contribution(s) was submitted. If You
8282+ institute patent litigation against any entity (including a
8383+ cross-claim or counterclaim in a lawsuit) alleging that the Work
8484+ or a Contribution incorporated within the Work constitutes direct
8585+ or contributory patent infringement, then any patent licenses
8686+ granted to You under this License for that Work shall terminate
8787+ as of the date such litigation is filed.
8888+8989+4. Redistribution. You may reproduce and distribute copies of the
9090+ Work or Derivative Works thereof in any medium, with or without
9191+ modifications, and in Source or Object form, provided that You
9292+ meet the following conditions:
9393+9494+ (a) You must give any other recipients of the Work or
9595+ Derivative Works a copy of this License; and
9696+9797+ (b) You must cause any modified files to carry prominent notices
9898+ stating that You changed the files; and
9999+100100+ (c) You must retain, in the Source form of any Derivative Works
101101+ that You distribute, all copyright, patent, trademark, and
102102+ attribution notices from the Source form of the Work,
103103+ excluding those notices that do not pertain to any part of
104104+ the Derivative Works; and
105105+106106+ (d) If the Work includes a "NOTICE" text file as part of its
107107+ distribution, then any Derivative Works that You distribute must
108108+ include a readable copy of the attribution notices contained
109109+ within such NOTICE file, excluding those notices that do not
110110+ pertain to any part of the Derivative Works, in at least one
111111+ of the following places: within a NOTICE text file distributed
112112+ as part of the Derivative Works; within the Source form or
113113+ documentation, if provided along with the Derivative Works; or,
114114+ within a display generated by the Derivative Works, if and
115115+ wherever such third-party notices normally appear. The contents
116116+ of the NOTICE file are for informational purposes only and
117117+ do not modify the License. You may add Your own attribution
118118+ notices within Derivative Works that You distribute, alongside
119119+ or as an addendum to the NOTICE text from the Work, provided
120120+ that such additional attribution notices cannot be construed
121121+ as modifying the License.
122122+123123+ You may add Your own copyright statement to Your modifications and
124124+ may provide additional or different license terms and conditions
125125+ for use, reproduction, or distribution of Your modifications, or
126126+ for any such Derivative Works as a whole, provided Your use,
127127+ reproduction, and distribution of the Work otherwise complies with
128128+ the conditions stated in this License.
129129+130130+5. Submission of Contributions. Unless You explicitly state otherwise,
131131+ any Contribution intentionally submitted for inclusion in the Work
132132+ by You to the Licensor shall be under the terms and conditions of
133133+ this License, without any additional terms or conditions.
134134+ Notwithstanding the above, nothing herein shall supersede or modify
135135+ the terms of any separate license agreement you may have executed
136136+ with Licensor regarding such Contributions.
137137+138138+6. Trademarks. This License does not grant permission to use the trade
139139+ names, trademarks, service marks, or product names of the Licensor,
140140+ except as required for reasonable and customary use in describing the
141141+ origin of the Work and reproducing the content of the NOTICE file.
142142+143143+7. Disclaimer of Warranty. Unless required by applicable law or
144144+ agreed to in writing, Licensor provides the Work (and each
145145+ Contributor provides its Contributions) on an "AS IS" BASIS,
146146+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147147+ implied, including, without limitation, any warranties or conditions
148148+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149149+ PARTICULAR PURPOSE. You are solely responsible for determining the
150150+ appropriateness of using or redistributing the Work and assume any
151151+ risks associated with Your exercise of permissions under this License.
152152+153153+8. Limitation of Liability. In no event and under no legal theory,
154154+ whether in tort (including negligence), contract, or otherwise,
155155+ unless required by applicable law (such as deliberate and grossly
156156+ negligent acts) or agreed to in writing, shall any Contributor be
157157+ liable to You for damages, including any direct, indirect, special,
158158+ incidental, or consequential damages of any character arising as a
159159+ result of this License or out of the use or inability to use the
160160+ Work (including but not limited to damages for loss of goodwill,
161161+ work stoppage, computer failure or malfunction, or any and all
162162+ other commercial damages or losses), even if such Contributor
163163+ has been advised of the possibility of such damages.
164164+165165+9. Accepting Warranty or Additional Liability. While redistributing
166166+ the Work or Derivative Works thereof, You may choose to offer,
167167+ and charge a fee for, acceptance of support, warranty, indemnity,
168168+ or other liability obligations and/or rights consistent with this
169169+ License. However, in accepting such obligations, You may act only
170170+ on Your own behalf and on Your sole responsibility, not on behalf
171171+ of any other Contributor, and only if You agree to indemnify,
172172+ defend, and hold each Contributor harmless for any liability
173173+ incurred by, or claims asserted against, such Contributor by reason
174174+ of your accepting any such warranty or additional liability.
175175+176176+END OF TERMS AND CONDITIONS
177177+178178+Copyright 2025 microcosm
179179+180180+Licensed under the Apache License, Version 2.0 (the "License");
181181+you may not use this file except in compliance with the License.
182182+You may obtain a copy of the License at
183183+184184+ http://www.apache.org/licenses/LICENSE-2.0
185185+186186+Unless required by applicable law or agreed to in writing, software
187187+distributed under the License is distributed on an "AS IS" BASIS,
188188+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
189189+See the License for the specific language governing permissions and
190190+limitations under the License.
+21
links/LICENSE.MIT
···11+MIT License
22+33+Copyright (c) 2025 microcosm
44+55+Permission is hereby granted, free of charge, to any person obtaining a copy
66+of this software and associated documentation files (the "Software"), to deal
77+in the Software without restriction, including without limitation the rights
88+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
99+copies of the Software, and to permit persons to whom the Software is
1010+furnished to do so, subject to the following conditions:
1111+1212+The above copyright notice and this permission notice shall be included in all
1313+copies or substantial portions of the Software.
1414+1515+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
1616+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
1717+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
1818+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
1919+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
2020+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
2121+SOFTWARE.
+12
links/readme.md
···11+## links
22+33+shared link-extraction logic
44+55+(desperately needed: finally write up a mini-spec kinda thing for how the link syntax works)
66+77+88+## license
99+1010+This work is dual-licensed under MIT and Apache 2.0. You can choose between one of them if you use this work.
1111+1212+`SPDX-License-Identifier: MIT OR Apache-2.0`
+44
links/src/did.rs
···77 // for now, just working through the rules laid out in the docs in order,
88 // without much regard for efficiency for now.
991010+ // newer specs say max 2048 chars
1111+ if s.len() > 2048 {
1212+ return None;
1313+ }
1414+1015 // The entire URI is made up of a subset of ASCII, containing letters (A-Z, a-z),
1116 // digits (0-9), period, underscore, colon, percent sign, or hyphen (._:%-)
1217 if !s
···6873#[cfg(test)]
6974mod tests {
7075 use super::*;
7676+7777+ #[test]
7878+ fn test_did_too_long() {
7979+ let long = concat!(
8080+ "did:long:zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz",
8181+ "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz",
8282+ "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz",
8383+ "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz",
8484+ "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz",
8585+ "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz",
8686+ "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz",
8787+ "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz",
8888+ "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz",
8989+ "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz",
9090+ "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz",
9191+ "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz",
9292+ "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz",
9393+ "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz",
9494+ "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz",
9595+ "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz",
9696+ "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz",
9797+ "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz",
9898+ "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz",
9999+ "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz",
100100+ "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz",
101101+ "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz",
102102+ "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz",
103103+ "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz",
104104+ "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz",
105105+ "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz",
106106+ "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz",
107107+ "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz",
108108+ "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz",
109109+ "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz",
110110+ "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz",
111111+ "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz",
112112+ );
113113+ assert_eq!(parse_did(long), None);
114114+ }
7111572116 #[test]
73117 fn test_did_parse() {
···11+[package]
22+name = "pocket"
33+version = "0.1.0"
44+edition = "2024"
55+66+[dependencies]
77+atrium-crypto = "0.1.2"
88+clap = { workspace = true }
99+jwt-compact = { git = "https://github.com/fatfingers23/jwt-compact.git", features = ["es256k"] }
1010+log = "0.4.27"
1111+poem = { version = "3.1.12", features = ["acme", "static-files"] }
1212+poem-openapi = { version = "5.1.16", features = ["scalar"] }
1313+reqwest = { version = "0.12.22", features = ["json"] }
1414+rusqlite = "0.37.0"
1515+serde = { version = "1.0.219", features = ["derive"] }
1616+serde_json = { version = "1.0.141" }
1717+thiserror = "2.0.16"
1818+tokio = { version = "1.47.0", features = ["full"] }
1919+tracing-subscriber = { version = "0.3.19", features = ["env-filter"] }
+190
pocket/LICENSE.Apache-2.0
···11+ Apache License
22+ Version 2.0, January 2004
33+ http://www.apache.org/licenses/
44+55+TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
66+77+1. Definitions.
88+99+ "License" shall mean the terms and conditions for use, reproduction,
1010+ and distribution as defined by Sections 1 through 9 of this document.
1111+1212+ "Licensor" shall mean the copyright owner or entity authorized by
1313+ the copyright owner that is granting the License.
1414+1515+ "Legal Entity" shall mean the union of the acting entity and all
1616+ other entities that control, are controlled by, or are under common
1717+ control with that entity. For the purposes of this definition,
1818+ "control" means (i) the power, direct or indirect, to cause the
1919+ direction or management of such entity, whether by contract or
2020+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
2121+ outstanding shares, or (iii) beneficial ownership of such entity.
2222+2323+ "You" (or "Your") shall mean an individual or Legal Entity
2424+ exercising permissions granted by this License.
2525+2626+ "Source" form shall mean the preferred form for making modifications,
2727+ including but not limited to software source code, documentation
2828+ source, and configuration files.
2929+3030+ "Object" form shall mean any form resulting from mechanical
3131+ transformation or translation of a Source form, including but
3232+ not limited to compiled object code, generated documentation,
3333+ and conversions to other media types.
3434+3535+ "Work" shall mean the work of authorship, whether in Source or
3636+ Object form, made available under the License, as indicated by a
3737+ copyright notice that is included in or attached to the work
3838+ (an example is provided in the Appendix below).
3939+4040+ "Derivative Works" shall mean any work, whether in Source or Object
4141+ form, that is based on (or derived from) the Work and for which the
4242+ editorial revisions, annotations, elaborations, or other modifications
4343+ represent, as a whole, an original work of authorship. For the purposes
4444+ of this License, Derivative Works shall not include works that remain
4545+ separable from, or merely link (or bind by name) to the interfaces of,
4646+ the Work and Derivative Works thereof.
4747+4848+ "Contribution" shall mean any work of authorship, including
4949+ the original version of the Work and any modifications or additions
5050+ to that Work or Derivative Works thereof, that is intentionally
5151+ submitted to Licensor for inclusion in the Work by the copyright owner
5252+ or by an individual or Legal Entity authorized to submit on behalf of
5353+ the copyright owner. For the purposes of this definition, "submitted"
5454+ means any form of electronic, verbal, or written communication sent
5555+ to the Licensor or its representatives, including but not limited to
5656+ communication on electronic mailing lists, source code control systems,
5757+ and issue tracking systems that are managed by, or on behalf of, the
5858+ Licensor for the purpose of discussing and improving the Work, but
5959+ excluding communication that is conspicuously marked or otherwise
6060+ designated in writing by the copyright owner as "Not a Contribution."
6161+6262+ "Contributor" shall mean Licensor and any individual or Legal Entity
6363+ on behalf of whom a Contribution has been received by Licensor and
6464+ subsequently incorporated within the Work.
6565+6666+2. Grant of Copyright License. Subject to the terms and conditions of
6767+ this License, each Contributor hereby grants to You a perpetual,
6868+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
6969+ copyright license to reproduce, prepare Derivative Works of,
7070+ publicly display, publicly perform, sublicense, and distribute the
7171+ Work and such Derivative Works in Source or Object form.
7272+7373+3. Grant of Patent License. Subject to the terms and conditions of
7474+ this License, each Contributor hereby grants to You a perpetual,
7575+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
7676+ (except as stated in this section) patent license to make, have made,
7777+ use, offer to sell, sell, import, and otherwise transfer the Work,
7878+ where such license applies only to those patent claims licensable
7979+ by such Contributor that are necessarily infringed by their
8080+ Contribution(s) alone or by combination of their Contribution(s)
8181+ with the Work to which such Contribution(s) was submitted. If You
8282+ institute patent litigation against any entity (including a
8383+ cross-claim or counterclaim in a lawsuit) alleging that the Work
8484+ or a Contribution incorporated within the Work constitutes direct
8585+ or contributory patent infringement, then any patent licenses
8686+ granted to You under this License for that Work shall terminate
8787+ as of the date such litigation is filed.
8888+8989+4. Redistribution. You may reproduce and distribute copies of the
9090+ Work or Derivative Works thereof in any medium, with or without
9191+ modifications, and in Source or Object form, provided that You
9292+ meet the following conditions:
9393+9494+ (a) You must give any other recipients of the Work or
9595+ Derivative Works a copy of this License; and
9696+9797+ (b) You must cause any modified files to carry prominent notices
9898+ stating that You changed the files; and
9999+100100+ (c) You must retain, in the Source form of any Derivative Works
101101+ that You distribute, all copyright, patent, trademark, and
102102+ attribution notices from the Source form of the Work,
103103+ excluding those notices that do not pertain to any part of
104104+ the Derivative Works; and
105105+106106+ (d) If the Work includes a "NOTICE" text file as part of its
107107+ distribution, then any Derivative Works that You distribute must
108108+ include a readable copy of the attribution notices contained
109109+ within such NOTICE file, excluding those notices that do not
110110+ pertain to any part of the Derivative Works, in at least one
111111+ of the following places: within a NOTICE text file distributed
112112+ as part of the Derivative Works; within the Source form or
113113+ documentation, if provided along with the Derivative Works; or,
114114+ within a display generated by the Derivative Works, if and
115115+ wherever such third-party notices normally appear. The contents
116116+ of the NOTICE file are for informational purposes only and
117117+ do not modify the License. You may add Your own attribution
118118+ notices within Derivative Works that You distribute, alongside
119119+ or as an addendum to the NOTICE text from the Work, provided
120120+ that such additional attribution notices cannot be construed
121121+ as modifying the License.
122122+123123+ You may add Your own copyright statement to Your modifications and
124124+ may provide additional or different license terms and conditions
125125+ for use, reproduction, or distribution of Your modifications, or
126126+ for any such Derivative Works as a whole, provided Your use,
127127+ reproduction, and distribution of the Work otherwise complies with
128128+ the conditions stated in this License.
129129+130130+5. Submission of Contributions. Unless You explicitly state otherwise,
131131+ any Contribution intentionally submitted for inclusion in the Work
132132+ by You to the Licensor shall be under the terms and conditions of
133133+ this License, without any additional terms or conditions.
134134+ Notwithstanding the above, nothing herein shall supersede or modify
135135+ the terms of any separate license agreement you may have executed
136136+ with Licensor regarding such Contributions.
137137+138138+6. Trademarks. This License does not grant permission to use the trade
139139+ names, trademarks, service marks, or product names of the Licensor,
140140+ except as required for reasonable and customary use in describing the
141141+ origin of the Work and reproducing the content of the NOTICE file.
142142+143143+7. Disclaimer of Warranty. Unless required by applicable law or
144144+ agreed to in writing, Licensor provides the Work (and each
145145+ Contributor provides its Contributions) on an "AS IS" BASIS,
146146+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147147+ implied, including, without limitation, any warranties or conditions
148148+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149149+ PARTICULAR PURPOSE. You are solely responsible for determining the
150150+ appropriateness of using or redistributing the Work and assume any
151151+ risks associated with Your exercise of permissions under this License.
152152+153153+8. Limitation of Liability. In no event and under no legal theory,
154154+ whether in tort (including negligence), contract, or otherwise,
155155+ unless required by applicable law (such as deliberate and grossly
156156+ negligent acts) or agreed to in writing, shall any Contributor be
157157+ liable to You for damages, including any direct, indirect, special,
158158+ incidental, or consequential damages of any character arising as a
159159+ result of this License or out of the use or inability to use the
160160+ Work (including but not limited to damages for loss of goodwill,
161161+ work stoppage, computer failure or malfunction, or any and all
162162+ other commercial damages or losses), even if such Contributor
163163+ has been advised of the possibility of such damages.
164164+165165+9. Accepting Warranty or Additional Liability. While redistributing
166166+ the Work or Derivative Works thereof, You may choose to offer,
167167+ and charge a fee for, acceptance of support, warranty, indemnity,
168168+ or other liability obligations and/or rights consistent with this
169169+ License. However, in accepting such obligations, You may act only
170170+ on Your own behalf and on Your sole responsibility, not on behalf
171171+ of any other Contributor, and only if You agree to indemnify,
172172+ defend, and hold each Contributor harmless for any liability
173173+ incurred by, or claims asserted against, such Contributor by reason
174174+ of your accepting any such warranty or additional liability.
175175+176176+END OF TERMS AND CONDITIONS
177177+178178+Copyright 2025 microcosm
179179+180180+Licensed under the Apache License, Version 2.0 (the "License");
181181+you may not use this file except in compliance with the License.
182182+You may obtain a copy of the License at
183183+184184+ http://www.apache.org/licenses/LICENSE-2.0
185185+186186+Unless required by applicable law or agreed to in writing, software
187187+distributed under the License is distributed on an "AS IS" BASIS,
188188+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
189189+See the License for the specific language governing permissions and
190190+limitations under the License.
+21
pocket/LICENSE.MIT
···11+MIT License
22+33+Copyright (c) 2025 microcosm
44+55+Permission is hereby granted, free of charge, to any person obtaining a copy
66+of this software and associated documentation files (the "Software"), to deal
77+in the Software without restriction, including without limitation the rights
88+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
99+copies of the Software, and to permit persons to whom the Software is
1010+furnished to do so, subject to the following conditions:
1111+1212+The above copyright notice and this permission notice shall be included in all
1313+copies or substantial portions of the Software.
1414+1515+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
1616+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
1717+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
1818+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
1919+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
2020+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
2121+SOFTWARE.
+17
pocket/api-description.md
···11+_A pocket dimension to stash a bit of non-public user data._
22+33+44+# Pocket: user preference storage
55+66+This API leverages atproto service proxying to offer a bit of per-user per-app non-public data storage.
77+Perfect for things like application preferences that might be better left out of the public PDS data.
88+99+The intent is to use oauth scopes to isolate storage on a per-application basis, and to allow easy data migration from a community hosted instance to your own if you end up needing that.
1010+1111+1212+### Current status
1313+1414+> [!important]
1515+> Pocket is currently in a **v0, pre-release state**. There is one production instance and you can use it! Expect short downtimes for restarts as development progresses and occaisional data loss until it's stable.
1616+1717+ATProto might end up adding a similar feature to [PDSs](https://atproto.com/guides/glossary#pds-personal-data-server). If/when that happens, you should use it instead of this!
+11
pocket/readme.md
···11+# pocket
22+33+pocket is a personal-private atproto data service, authorized by PDS service proxying or `com.atproto.server.getServiceAuth`.
44+55+_status: early development, lots still to do_
66+77+## license
88+99+This work is dual-licensed under MIT and Apache 2.0. You can choose between one of them if you use this work.
1010+1111+`SPDX-License-Identifier: MIT OR Apache-2.0`
+7
pocket/src/lib.rs
···11+mod server;
22+mod storage;
33+mod token;
44+55+pub use server::serve;
66+pub use storage::Storage;
77+pub use token::TokenVerifier;
+34
pocket/src/main.rs
···11+use clap::Parser;
22+use pocket::{Storage, serve};
33+use std::path::PathBuf;
44+55+/// Slingshot record edge cache
66+#[derive(Parser, Debug, Clone)]
77+#[command(version, about, long_about = None)]
88+struct Args {
99+ /// path to the sqlite db file
1010+ #[arg(long)]
1111+ db: Option<PathBuf>,
1212+ /// just initialize the db and exit
1313+ #[arg(long, action)]
1414+ init_db: bool,
1515+ /// the domain for serving a did doc (unused if running behind reflector)
1616+ #[arg(long)]
1717+ domain: Option<String>,
1818+}
1919+2020+#[tokio::main]
2121+async fn main() {
2222+ tracing_subscriber::fmt::init();
2323+ log::info!("👖 hi");
2424+ let args = Args::parse();
2525+ let domain = args.domain.unwrap_or("bad-example.com".into());
2626+ let db_path = args.db.unwrap_or("prefs.sqlite3".into());
2727+ if args.init_db {
2828+ Storage::init(&db_path).unwrap();
2929+ log::info!("👖 initialized db at {db_path:?}. bye")
3030+ } else {
3131+ let storage = Storage::connect(db_path).unwrap();
3232+ serve(&domain, storage).await
3333+ }
3434+}
···11+ Apache License
22+ Version 2.0, January 2004
33+ http://www.apache.org/licenses/
44+55+TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
66+77+1. Definitions.
88+99+ "License" shall mean the terms and conditions for use, reproduction,
1010+ and distribution as defined by Sections 1 through 9 of this document.
1111+1212+ "Licensor" shall mean the copyright owner or entity authorized by
1313+ the copyright owner that is granting the License.
1414+1515+ "Legal Entity" shall mean the union of the acting entity and all
1616+ other entities that control, are controlled by, or are under common
1717+ control with that entity. For the purposes of this definition,
1818+ "control" means (i) the power, direct or indirect, to cause the
1919+ direction or management of such entity, whether by contract or
2020+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
2121+ outstanding shares, or (iii) beneficial ownership of such entity.
2222+2323+ "You" (or "Your") shall mean an individual or Legal Entity
2424+ exercising permissions granted by this License.
2525+2626+ "Source" form shall mean the preferred form for making modifications,
2727+ including but not limited to software source code, documentation
2828+ source, and configuration files.
2929+3030+ "Object" form shall mean any form resulting from mechanical
3131+ transformation or translation of a Source form, including but
3232+ not limited to compiled object code, generated documentation,
3333+ and conversions to other media types.
3434+3535+ "Work" shall mean the work of authorship, whether in Source or
3636+ Object form, made available under the License, as indicated by a
3737+ copyright notice that is included in or attached to the work
3838+ (an example is provided in the Appendix below).
3939+4040+ "Derivative Works" shall mean any work, whether in Source or Object
4141+ form, that is based on (or derived from) the Work and for which the
4242+ editorial revisions, annotations, elaborations, or other modifications
4343+ represent, as a whole, an original work of authorship. For the purposes
4444+ of this License, Derivative Works shall not include works that remain
4545+ separable from, or merely link (or bind by name) to the interfaces of,
4646+ the Work and Derivative Works thereof.
4747+4848+ "Contribution" shall mean any work of authorship, including
4949+ the original version of the Work and any modifications or additions
5050+ to that Work or Derivative Works thereof, that is intentionally
5151+ submitted to Licensor for inclusion in the Work by the copyright owner
5252+ or by an individual or Legal Entity authorized to submit on behalf of
5353+ the copyright owner. For the purposes of this definition, "submitted"
5454+ means any form of electronic, verbal, or written communication sent
5555+ to the Licensor or its representatives, including but not limited to
5656+ communication on electronic mailing lists, source code control systems,
5757+ and issue tracking systems that are managed by, or on behalf of, the
5858+ Licensor for the purpose of discussing and improving the Work, but
5959+ excluding communication that is conspicuously marked or otherwise
6060+ designated in writing by the copyright owner as "Not a Contribution."
6161+6262+ "Contributor" shall mean Licensor and any individual or Legal Entity
6363+ on behalf of whom a Contribution has been received by Licensor and
6464+ subsequently incorporated within the Work.
6565+6666+2. Grant of Copyright License. Subject to the terms and conditions of
6767+ this License, each Contributor hereby grants to You a perpetual,
6868+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
6969+ copyright license to reproduce, prepare Derivative Works of,
7070+ publicly display, publicly perform, sublicense, and distribute the
7171+ Work and such Derivative Works in Source or Object form.
7272+7373+3. Grant of Patent License. Subject to the terms and conditions of
7474+ this License, each Contributor hereby grants to You a perpetual,
7575+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
7676+ (except as stated in this section) patent license to make, have made,
7777+ use, offer to sell, sell, import, and otherwise transfer the Work,
7878+ where such license applies only to those patent claims licensable
7979+ by such Contributor that are necessarily infringed by their
8080+ Contribution(s) alone or by combination of their Contribution(s)
8181+ with the Work to which such Contribution(s) was submitted. If You
8282+ institute patent litigation against any entity (including a
8383+ cross-claim or counterclaim in a lawsuit) alleging that the Work
8484+ or a Contribution incorporated within the Work constitutes direct
8585+ or contributory patent infringement, then any patent licenses
8686+ granted to You under this License for that Work shall terminate
8787+ as of the date such litigation is filed.
8888+8989+4. Redistribution. You may reproduce and distribute copies of the
9090+ Work or Derivative Works thereof in any medium, with or without
9191+ modifications, and in Source or Object form, provided that You
9292+ meet the following conditions:
9393+9494+ (a) You must give any other recipients of the Work or
9595+ Derivative Works a copy of this License; and
9696+9797+ (b) You must cause any modified files to carry prominent notices
9898+ stating that You changed the files; and
9999+100100+ (c) You must retain, in the Source form of any Derivative Works
101101+ that You distribute, all copyright, patent, trademark, and
102102+ attribution notices from the Source form of the Work,
103103+ excluding those notices that do not pertain to any part of
104104+ the Derivative Works; and
105105+106106+ (d) If the Work includes a "NOTICE" text file as part of its
107107+ distribution, then any Derivative Works that You distribute must
108108+ include a readable copy of the attribution notices contained
109109+ within such NOTICE file, excluding those notices that do not
110110+ pertain to any part of the Derivative Works, in at least one
111111+ of the following places: within a NOTICE text file distributed
112112+ as part of the Derivative Works; within the Source form or
113113+ documentation, if provided along with the Derivative Works; or,
114114+ within a display generated by the Derivative Works, if and
115115+ wherever such third-party notices normally appear. The contents
116116+ of the NOTICE file are for informational purposes only and
117117+ do not modify the License. You may add Your own attribution
118118+ notices within Derivative Works that You distribute, alongside
119119+ or as an addendum to the NOTICE text from the Work, provided
120120+ that such additional attribution notices cannot be construed
121121+ as modifying the License.
122122+123123+ You may add Your own copyright statement to Your modifications and
124124+ may provide additional or different license terms and conditions
125125+ for use, reproduction, or distribution of Your modifications, or
126126+ for any such Derivative Works as a whole, provided Your use,
127127+ reproduction, and distribution of the Work otherwise complies with
128128+ the conditions stated in this License.
129129+130130+5. Submission of Contributions. Unless You explicitly state otherwise,
131131+ any Contribution intentionally submitted for inclusion in the Work
132132+ by You to the Licensor shall be under the terms and conditions of
133133+ this License, without any additional terms or conditions.
134134+ Notwithstanding the above, nothing herein shall supersede or modify
135135+ the terms of any separate license agreement you may have executed
136136+ with Licensor regarding such Contributions.
137137+138138+6. Trademarks. This License does not grant permission to use the trade
139139+ names, trademarks, service marks, or product names of the Licensor,
140140+ except as required for reasonable and customary use in describing the
141141+ origin of the Work and reproducing the content of the NOTICE file.
142142+143143+7. Disclaimer of Warranty. Unless required by applicable law or
144144+ agreed to in writing, Licensor provides the Work (and each
145145+ Contributor provides its Contributions) on an "AS IS" BASIS,
146146+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147147+ implied, including, without limitation, any warranties or conditions
148148+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149149+ PARTICULAR PURPOSE. You are solely responsible for determining the
150150+ appropriateness of using or redistributing the Work and assume any
151151+ risks associated with Your exercise of permissions under this License.
152152+153153+8. Limitation of Liability. In no event and under no legal theory,
154154+ whether in tort (including negligence), contract, or otherwise,
155155+ unless required by applicable law (such as deliberate and grossly
156156+ negligent acts) or agreed to in writing, shall any Contributor be
157157+ liable to You for damages, including any direct, indirect, special,
158158+ incidental, or consequential damages of any character arising as a
159159+ result of this License or out of the use or inability to use the
160160+ Work (including but not limited to damages for loss of goodwill,
161161+ work stoppage, computer failure or malfunction, or any and all
162162+ other commercial damages or losses), even if such Contributor
163163+ has been advised of the possibility of such damages.
164164+165165+9. Accepting Warranty or Additional Liability. While redistributing
166166+ the Work or Derivative Works thereof, You may choose to offer,
167167+ and charge a fee for, acceptance of support, warranty, indemnity,
168168+ or other liability obligations and/or rights consistent with this
169169+ License. However, in accepting such obligations, You may act only
170170+ on Your own behalf and on Your sole responsibility, not on behalf
171171+ of any other Contributor, and only if You agree to indemnify,
172172+ defend, and hold each Contributor harmless for any liability
173173+ incurred by, or claims asserted against, such Contributor by reason
174174+ of your accepting any such warranty or additional liability.
175175+176176+END OF TERMS AND CONDITIONS
177177+178178+Copyright 2025 microcosm
179179+180180+Licensed under the Apache License, Version 2.0 (the "License");
181181+you may not use this file except in compliance with the License.
182182+You may obtain a copy of the License at
183183+184184+ http://www.apache.org/licenses/LICENSE-2.0
185185+186186+Unless required by applicable law or agreed to in writing, software
187187+distributed under the License is distributed on an "AS IS" BASIS,
188188+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
189189+See the License for the specific language governing permissions and
190190+limitations under the License.
+21
quasar/LICENSE.MIT
···11+MIT License
22+33+Copyright (c) 2025 microcosm
44+55+Permission is hereby granted, free of charge, to any person obtaining a copy
66+of this software and associated documentation files (the "Software"), to deal
77+in the Software without restriction, including without limitation the rights
88+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
99+copies of the Software, and to permit persons to whom the Software is
1010+furnished to do so, subject to the following conditions:
1111+1212+The above copyright notice and this permission notice shall be included in all
1313+copies or substantial portions of the Software.
1414+1515+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
1616+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
1717+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
1818+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
1919+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
2020+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
2121+SOFTWARE.
+10
quasar/readme.md
···11+# quasar
22+33+indexed replay and fan-out for event stream services (wip)
44+55+66+## license
77+88+This work is dual-licensed under MIT and Apache 2.0. You can choose between one of them if you use this work.
99+1010+`SPDX-License-Identifier: MIT OR Apache-2.0`
+3
quasar/src/lib.rs
···11+mod storage;
22+33+pub use storage::Storage;
···1010Tutorials, how-to guides, and client SDK libraries are all in the works for gentler on-ramps, but are not quite ready yet. But don't let that stop you! Hop in the [microcosm discord](https://discord.gg/tcDfe4PGVB), or post questions and tag [@bad-example.com](https://bsky.app/profile/bad-example.com) on Bluesky if you get stuck anywhere.
11111212> [!tip]
1313-> This repository's primary home is moving to tangled: [@microcosm.blue/microcosm-rs](https://tangled.sh/@microcosm.blue/microcosm-rs). It will continue to be mirrored on [github](https://github.com/at-microcosm/microcosm-rs) for the forseeable future, and it's fine to open issues or pulls in either place!
1313+> This repository's primary home is moving to tangled: [@microcosm.blue/microcosm-rs](https://tangled.org/microcosm.blue/microcosm-rs). It will continue to be mirrored on [github](https://github.com/at-microcosm/microcosm-rs) for the forseeable future, and it's fine to open issues or pulls in either place!
141415151616🌌 [Constellation](./constellation/)
···8282> See also: [Rocketman](https://github.com/teal-fm/cadet/tree/main/rocketman), another excellent rust jetstream client which shares some lineage and _is_ published on crates.io.
838384848585-8686-🔭 Deprecated: [Who am I](./who-am-i)
8585+🔭 Deprecated: [Who am I](./legacy/who-am-i)
8786-------------------------------------
88878988An identity bridge for microcosm demos, that kinda worked. Fixing its problems is about equivalent to reinventing a lot of OIDC, so it's being retired.
90899191-- Source: [./who-am-i/](./who-am-i/)
9090+- Source: [./who-am-i/](./legacy/who-am-i/)
9291- Status: ready for retirement.
93929493> [!warning]
9594> `who-am-i` is still in use for the Spacedust Notifications demo, but that will hopefully be migrated to use atproto oauth directly instead.
9595+9696+9797+🪩 Deprecated: [Reflector](./legacy/reflector)
9898+----------------------------------------------
9999+100100+a tiny did:web service server that maps subdomains to a single service endpoint
101101+102102+103103+License
104104+-------
105105+106106+Individual projects in this repo may differ in their licenses -- a missing license file in any project folder is a bug. Please open an issue if you notice one has been overlooked.
+4-4
slingshot/Cargo.toml
···88atrium-common = { git = "https://github.com/uniphil/atrium.git", branch = "fix/resolve-handle-https-accept-whitespace" }
99atrium-identity = { git = "https://github.com/uniphil/atrium.git", branch = "fix/resolve-handle-https-accept-whitespace" }
1010atrium-oauth = { git = "https://github.com/uniphil/atrium.git", branch = "fix/resolve-handle-https-accept-whitespace" }
1111-clap = { version = "4.5.41", features = ["derive"] }
1111+clap = { workspace = true }
1212ctrlc = "3.4.7"
1313-foyer = { version = "0.18.0", features = ["serde"] }
1313+foyer = { version = "0.22.3", features = ["serde"] }
1414hickory-resolver = "0.25.2"
1515jetstream = { path = "../jetstream", features = ["metrics"] }
1616-links = { path = "../links" }
1616+microcosm-links = { path = "../links" }
1717log = "0.4.27"
1818metrics = "0.24.2"
1919metrics-exporter-prometheus = { version = "0.17.1", features = ["http-listener"] }
···2424serde = { version = "1.0.219", features = ["derive"] }
2525serde_json = { version = "1.0.141", features = ["raw_value"] }
2626thiserror = "2.0.12"
2727-time = { version = "0.3.41", features = ["serde"] }
2727+time = { version = "0.3.47", features = ["serde"] }
2828tokio = { version = "1.47.0", features = ["full"] }
2929tokio-util = "0.7.15"
3030tracing-subscriber = { version = "0.3.19", features = ["env-filter"] }
+190
slingshot/LICENSE.Apache-2.0
···11+ Apache License
22+ Version 2.0, January 2004
33+ http://www.apache.org/licenses/
44+55+TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
66+77+1. Definitions.
88+99+ "License" shall mean the terms and conditions for use, reproduction,
1010+ and distribution as defined by Sections 1 through 9 of this document.
1111+1212+ "Licensor" shall mean the copyright owner or entity authorized by
1313+ the copyright owner that is granting the License.
1414+1515+ "Legal Entity" shall mean the union of the acting entity and all
1616+ other entities that control, are controlled by, or are under common
1717+ control with that entity. For the purposes of this definition,
1818+ "control" means (i) the power, direct or indirect, to cause the
1919+ direction or management of such entity, whether by contract or
2020+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
2121+ outstanding shares, or (iii) beneficial ownership of such entity.
2222+2323+ "You" (or "Your") shall mean an individual or Legal Entity
2424+ exercising permissions granted by this License.
2525+2626+ "Source" form shall mean the preferred form for making modifications,
2727+ including but not limited to software source code, documentation
2828+ source, and configuration files.
2929+3030+ "Object" form shall mean any form resulting from mechanical
3131+ transformation or translation of a Source form, including but
3232+ not limited to compiled object code, generated documentation,
3333+ and conversions to other media types.
3434+3535+ "Work" shall mean the work of authorship, whether in Source or
3636+ Object form, made available under the License, as indicated by a
3737+ copyright notice that is included in or attached to the work
3838+ (an example is provided in the Appendix below).
3939+4040+ "Derivative Works" shall mean any work, whether in Source or Object
4141+ form, that is based on (or derived from) the Work and for which the
4242+ editorial revisions, annotations, elaborations, or other modifications
4343+ represent, as a whole, an original work of authorship. For the purposes
4444+ of this License, Derivative Works shall not include works that remain
4545+ separable from, or merely link (or bind by name) to the interfaces of,
4646+ the Work and Derivative Works thereof.
4747+4848+ "Contribution" shall mean any work of authorship, including
4949+ the original version of the Work and any modifications or additions
5050+ to that Work or Derivative Works thereof, that is intentionally
5151+ submitted to Licensor for inclusion in the Work by the copyright owner
5252+ or by an individual or Legal Entity authorized to submit on behalf of
5353+ the copyright owner. For the purposes of this definition, "submitted"
5454+ means any form of electronic, verbal, or written communication sent
5555+ to the Licensor or its representatives, including but not limited to
5656+ communication on electronic mailing lists, source code control systems,
5757+ and issue tracking systems that are managed by, or on behalf of, the
5858+ Licensor for the purpose of discussing and improving the Work, but
5959+ excluding communication that is conspicuously marked or otherwise
6060+ designated in writing by the copyright owner as "Not a Contribution."
6161+6262+ "Contributor" shall mean Licensor and any individual or Legal Entity
6363+ on behalf of whom a Contribution has been received by Licensor and
6464+ subsequently incorporated within the Work.
6565+6666+2. Grant of Copyright License. Subject to the terms and conditions of
6767+ this License, each Contributor hereby grants to You a perpetual,
6868+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
6969+ copyright license to reproduce, prepare Derivative Works of,
7070+ publicly display, publicly perform, sublicense, and distribute the
7171+ Work and such Derivative Works in Source or Object form.
7272+7373+3. Grant of Patent License. Subject to the terms and conditions of
7474+ this License, each Contributor hereby grants to You a perpetual,
7575+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
7676+ (except as stated in this section) patent license to make, have made,
7777+ use, offer to sell, sell, import, and otherwise transfer the Work,
7878+ where such license applies only to those patent claims licensable
7979+ by such Contributor that are necessarily infringed by their
8080+ Contribution(s) alone or by combination of their Contribution(s)
8181+ with the Work to which such Contribution(s) was submitted. If You
8282+ institute patent litigation against any entity (including a
8383+ cross-claim or counterclaim in a lawsuit) alleging that the Work
8484+ or a Contribution incorporated within the Work constitutes direct
8585+ or contributory patent infringement, then any patent licenses
8686+ granted to You under this License for that Work shall terminate
8787+ as of the date such litigation is filed.
8888+8989+4. Redistribution. You may reproduce and distribute copies of the
9090+ Work or Derivative Works thereof in any medium, with or without
9191+ modifications, and in Source or Object form, provided that You
9292+ meet the following conditions:
9393+9494+ (a) You must give any other recipients of the Work or
9595+ Derivative Works a copy of this License; and
9696+9797+ (b) You must cause any modified files to carry prominent notices
9898+ stating that You changed the files; and
9999+100100+ (c) You must retain, in the Source form of any Derivative Works
101101+ that You distribute, all copyright, patent, trademark, and
102102+ attribution notices from the Source form of the Work,
103103+ excluding those notices that do not pertain to any part of
104104+ the Derivative Works; and
105105+106106+ (d) If the Work includes a "NOTICE" text file as part of its
107107+ distribution, then any Derivative Works that You distribute must
108108+ include a readable copy of the attribution notices contained
109109+ within such NOTICE file, excluding those notices that do not
110110+ pertain to any part of the Derivative Works, in at least one
111111+ of the following places: within a NOTICE text file distributed
112112+ as part of the Derivative Works; within the Source form or
113113+ documentation, if provided along with the Derivative Works; or,
114114+ within a display generated by the Derivative Works, if and
115115+ wherever such third-party notices normally appear. The contents
116116+ of the NOTICE file are for informational purposes only and
117117+ do not modify the License. You may add Your own attribution
118118+ notices within Derivative Works that You distribute, alongside
119119+ or as an addendum to the NOTICE text from the Work, provided
120120+ that such additional attribution notices cannot be construed
121121+ as modifying the License.
122122+123123+ You may add Your own copyright statement to Your modifications and
124124+ may provide additional or different license terms and conditions
125125+ for use, reproduction, or distribution of Your modifications, or
126126+ for any such Derivative Works as a whole, provided Your use,
127127+ reproduction, and distribution of the Work otherwise complies with
128128+ the conditions stated in this License.
129129+130130+5. Submission of Contributions. Unless You explicitly state otherwise,
131131+ any Contribution intentionally submitted for inclusion in the Work
132132+ by You to the Licensor shall be under the terms and conditions of
133133+ this License, without any additional terms or conditions.
134134+ Notwithstanding the above, nothing herein shall supersede or modify
135135+ the terms of any separate license agreement you may have executed
136136+ with Licensor regarding such Contributions.
137137+138138+6. Trademarks. This License does not grant permission to use the trade
139139+ names, trademarks, service marks, or product names of the Licensor,
140140+ except as required for reasonable and customary use in describing the
141141+ origin of the Work and reproducing the content of the NOTICE file.
142142+143143+7. Disclaimer of Warranty. Unless required by applicable law or
144144+ agreed to in writing, Licensor provides the Work (and each
145145+ Contributor provides its Contributions) on an "AS IS" BASIS,
146146+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147147+ implied, including, without limitation, any warranties or conditions
148148+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149149+ PARTICULAR PURPOSE. You are solely responsible for determining the
150150+ appropriateness of using or redistributing the Work and assume any
151151+ risks associated with Your exercise of permissions under this License.
152152+153153+8. Limitation of Liability. In no event and under no legal theory,
154154+ whether in tort (including negligence), contract, or otherwise,
155155+ unless required by applicable law (such as deliberate and grossly
156156+ negligent acts) or agreed to in writing, shall any Contributor be
157157+ liable to You for damages, including any direct, indirect, special,
158158+ incidental, or consequential damages of any character arising as a
159159+ result of this License or out of the use or inability to use the
160160+ Work (including but not limited to damages for loss of goodwill,
161161+ work stoppage, computer failure or malfunction, or any and all
162162+ other commercial damages or losses), even if such Contributor
163163+ has been advised of the possibility of such damages.
164164+165165+9. Accepting Warranty or Additional Liability. While redistributing
166166+ the Work or Derivative Works thereof, You may choose to offer,
167167+ and charge a fee for, acceptance of support, warranty, indemnity,
168168+ or other liability obligations and/or rights consistent with this
169169+ License. However, in accepting such obligations, You may act only
170170+ on Your own behalf and on Your sole responsibility, not on behalf
171171+ of any other Contributor, and only if You agree to indemnify,
172172+ defend, and hold each Contributor harmless for any liability
173173+ incurred by, or claims asserted against, such Contributor by reason
174174+ of your accepting any such warranty or additional liability.
175175+176176+END OF TERMS AND CONDITIONS
177177+178178+Copyright 2025 microcosm
179179+180180+Licensed under the Apache License, Version 2.0 (the "License");
181181+you may not use this file except in compliance with the License.
182182+You may obtain a copy of the License at
183183+184184+ http://www.apache.org/licenses/LICENSE-2.0
185185+186186+Unless required by applicable law or agreed to in writing, software
187187+distributed under the License is distributed on an "AS IS" BASIS,
188188+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
189189+See the License for the specific language governing permissions and
190190+limitations under the License.
+21
slingshot/LICENSE.MIT
···11+MIT License
22+33+Copyright (c) 2025 microcosm
44+55+Permission is hereby granted, free of charge, to any person obtaining a copy
66+of this software and associated documentation files (the "Software"), to deal
77+in the Software without restriction, including without limitation the rights
88+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
99+copies of the Software, and to permit persons to whom the Software is
1010+furnished to do so, subject to the following conditions:
1111+1212+The above copyright notice and this permission notice shall be included in all
1313+copies or substantial portions of the Software.
1414+1515+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
1616+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
1717+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
1818+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
1919+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
2020+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
2121+SOFTWARE.
+2-2
slingshot/api-description.md
···11_A [gravitational slingshot](https://en.wikipedia.org/wiki/Gravity_assist) makes use of the gravity and relative movements of celestial bodies to accelerate a spacecraft and change its trajectory._
223344-# Slingshot: edge record cache
44+# Slingshot: edge record and identity cache
5566Applications in [ATProtocol](https://atproto.com/) store data in users' own [PDS](https://atproto.com/guides/self-hosting) (Personal Data Server), which are distributed across thousands of independently-run servers all over the world. Trying to access this data poses challenges for client applications:
77···9090- [🎇 Spacedust](https://spacedust.microcosm.blue/), a firehose of all social interactions
91919292> [!success]
9393-> All microcosm projects are [open source](https://tangled.sh/@bad-example.com/microcosm-links). **You can help sustain Slingshot** and all of microcosm by becoming a [Github sponsor](https://github.com/sponsors/uniphil/) or a [Ko-fi supporter](https://ko-fi.com/bad_example)!
9393+> All microcosm projects are [open source](https://tangled.org/bad-example.com/microcosm-links). **You can help sustain Slingshot** and all of microcosm by becoming a [Github sponsor](https://github.com/sponsors/uniphil/) or a [Ko-fi supporter](https://ko-fi.com/bad_example)!
+41
slingshot/readme.md
···55```bash
66RUST_LOG=info,slingshot=trace ulimit -n 4096 && RUST_LOG=info cargo run -- --jetstream us-east-1 --cache-dir ./foyer
77```
88+99+the identity cache uses a lot of files so you probably need to bump ulimit
1010+1111+on macos:
1212+1313+```bash
1414+ulimit -n 4096
1515+```
1616+1717+## prod deploy
1818+1919+you **must** setcap the binary to run it on apollo!!!!
2020+2121+```bash
2222+sudo setcap CAP_NET_BIND_SERVICE=+eip ../target/release/slingshot
2323+```
2424+2525+then run with
2626+2727+```bash
2828+RUST_BACKTRACE=1 RUST_LOG=info,slingshot=trace /home/ubuntu/links/target/release/slingshot \
2929+ --jetstream wss://jetstream1.us-east.fire.hose.cam/subscribe \
3030+ --healthcheck https://hc-ping.com/[REDACTED] \
3131+ --cache-dir ./foyer \
3232+ --record-cache-memory-mb 2048 \
3333+ --record-cache-disk-gb 32 \
3434+ --identity-cache-memory-mb 1024 \
3535+ --identity-cache-disk-gb 8 \
3636+ --collect-metrics \
3737+ --acme-ipv6 \
3838+ --acme-domain slingshot.microcosm.blue \
3939+ --acme-contact phil@bad-example.com \
4040+ --acme-cache-path /home/ubuntu/certs
4141+```
4242+4343+4444+## license
4545+4646+This work is dual-licensed under MIT and Apache 2.0. You can choose between one of them if you use this work.
4747+4848+`SPDX-License-Identifier: MIT OR Apache-2.0`
···1111/// 1. handle -> DID resolution: getRecord must accept a handle for `repo` param
1212/// 2. DID -> PDS resolution: so we know where to getRecord
1313/// 3. DID -> handle resolution: for bidirectional handle validation and in case we want to offer this
1414-use std::time::Duration;
1414+use std::time::{Duration, Instant};
1515use tokio::sync::Mutex;
1616use tokio_util::sync::CancellationToken;
1717···2626 handle::{AtprotoHandleResolver, AtprotoHandleResolverConfig, DnsTxtResolver},
2727};
2828use atrium_oauth::DefaultHttpClient; // it's probably not worth bringing all of atrium_oauth for this but
2929-use foyer::{DirectFsDeviceOptions, Engine, HybridCache, HybridCacheBuilder};
2929+use foyer::{
3030+ BlockEngineConfig, DeviceBuilder, FsDeviceBuilder, HybridCache, HybridCacheBuilder,
3131+ PsyncIoEngineConfig,
3232+};
3033use serde::{Deserialize, Serialize};
3134use time::UtcDateTime;
3235···3538const MIN_NOT_FOUND_TTL: Duration = Duration::from_secs(60);
36393740#[derive(Debug, Clone, Hash, PartialEq, Eq, Serialize, Deserialize)]
3838-enum IdentityKey {
4141+pub enum IdentityKey {
3942 Handle(Handle),
4043 Did(Did),
4144}
42454646+impl IdentityKey {
4747+ fn weight(&self) -> usize {
4848+ let s = match self {
4949+ IdentityKey::Handle(h) => h.as_str(),
5050+ IdentityKey::Did(d) => d.as_str(),
5151+ };
5252+ std::mem::size_of::<Self>() + std::mem::size_of_val(s)
5353+ }
5454+}
5555+4356#[derive(Debug, Serialize, Deserialize)]
4457struct IdentityVal(UtcDateTime, IdentityData);
4558···5063 Doc(PartialMiniDoc),
5164}
52656666+impl IdentityVal {
6767+ fn weight(&self) -> usize {
6868+ let wrapping = std::mem::size_of::<Self>();
6969+ let inner = match &self.1 {
7070+ IdentityData::NotFound => 0,
7171+ IdentityData::Did(d) => std::mem::size_of_val(d.as_str()),
7272+ IdentityData::Doc(d) => {
7373+ std::mem::size_of_val(d.unverified_handle.as_str())
7474+ + std::mem::size_of_val(d.pds.as_str())
7575+ + std::mem::size_of_val(d.signing_key.as_str())
7676+ }
7777+ };
7878+ wrapping + inner
7979+ }
8080+}
8181+5382/// partial representation of a com.bad-example.identity mini atproto doc
5483///
5584/// partial because the handle is not verified
···86115 let Some(maybe_handle) = aka.strip_prefix("at://") else {
87116 continue;
88117 };
8989- let Ok(valid_handle) = Handle::new(maybe_handle.to_string()) else {
118118+ let Ok(valid_handle) = Handle::new(maybe_handle.to_lowercase()) else {
90119 continue;
91120 };
92121 unverified_handle = Some(valid_handle);
···157186 /// multi-producer *single consumer* queue
158187 refresh_queue: Arc<Mutex<RefreshQueue>>,
159188 /// just a lock to ensure only one refresher (queue consumer) is running (to be improved with a better refresher)
160160- refresher: Arc<Mutex<()>>,
189189+ refresher_task: Arc<Mutex<()>>,
161190}
162191163192impl Identity {
164164- pub async fn new(cache_dir: impl AsRef<Path>) -> Result<Self, IdentityError> {
193193+ pub async fn new(
194194+ cache_dir: impl AsRef<Path>,
195195+ memory_mb: usize,
196196+ disk_gb: usize,
197197+ ) -> Result<Self, IdentityError> {
165198 let http_client = Arc::new(DefaultHttpClient::default());
166199 let handle_resolver = AtprotoHandleResolver::new(AtprotoHandleResolverConfig {
167200 dns_txt_resolver: HickoryDnsTxtResolver::new().unwrap(),
···171204 plc_directory_url: DEFAULT_PLC_DIRECTORY_URL.to_string(),
172205 http_client: http_client.clone(),
173206 });
207207+208208+ let device = FsDeviceBuilder::new(cache_dir)
209209+ .with_capacity(disk_gb * 2_usize.pow(30))
210210+ .build()?;
211211+ let engine = BlockEngineConfig::new(device).with_block_size(2_usize.pow(20)); // note: this does limit the max cached item size
174212175213 let cache = HybridCacheBuilder::new()
176214 .with_name("identity")
177177- .memory(16 * 2_usize.pow(20))
178178- .with_weighter(|k, v| std::mem::size_of_val(k) + std::mem::size_of_val(v))
179179- .storage(Engine::small())
180180- .with_device_options(
181181- DirectFsDeviceOptions::new(cache_dir)
182182- .with_capacity(2_usize.pow(30)) // TODO: configurable (1GB to have something)
183183- .with_file_size(2_usize.pow(20)), // note: this does limit the max cached item size, warning jumbo records
184184- )
215215+ .memory(memory_mb * 2_usize.pow(20))
216216+ .with_weighter(|k: &IdentityKey, v: &IdentityVal| k.weight() + v.weight())
217217+ .storage()
218218+ .with_io_engine_config(PsyncIoEngineConfig::default())
219219+ .with_engine_config(engine)
185220 .build()
186221 .await?;
187222···190225 did_resolver: Arc::new(did_resolver),
191226 cache,
192227 refresh_queue: Default::default(),
193193- refresher: Default::default(),
228228+ refresher_task: Default::default(),
194229 })
195230 }
196231···229264 handle: &Handle,
230265 ) -> Result<Option<Did>, IdentityError> {
231266 let key = IdentityKey::Handle(handle.clone());
267267+ metrics::counter!("slingshot_get_handle").increment(1);
232268 let entry = self
233269 .cache
234234- .fetch(key.clone(), {
270270+ .get_or_fetch(&key, {
235271 let handle = handle.clone();
236272 let resolver = self.handle_resolver.clone();
237273 || async move {
238238- match resolver.resolve(&handle).await {
239239- Ok(did) => Ok(IdentityVal(UtcDateTime::now(), IdentityData::Did(did))),
240240- Err(atrium_identity::Error::NotFound) => {
241241- Ok(IdentityVal(UtcDateTime::now(), IdentityData::NotFound))
242242- }
243243- Err(other) => Err(foyer::Error::Other(Box::new({
274274+ let t0 = Instant::now();
275275+ let (res, success) = match resolver.resolve(&handle).await {
276276+ Ok(did) => (
277277+ Ok(IdentityVal(UtcDateTime::now(), IdentityData::Did(did))),
278278+ "true",
279279+ ),
280280+ Err(atrium_identity::Error::NotFound) => (
281281+ Ok(IdentityVal(UtcDateTime::now(), IdentityData::NotFound)),
282282+ "false",
283283+ ),
284284+ Err(other) => {
244285 log::debug!("other error resolving handle: {other:?}");
245245- IdentityError::ResolutionFailed(other)
246246- }))),
247247- }
286286+ (Err(IdentityError::ResolutionFailed(other)), "false")
287287+ }
288288+ };
289289+ metrics::histogram!("slingshot_fetch_handle", "success" => success)
290290+ .record(t0.elapsed());
291291+ res
248292 }
249293 })
250294 .await?;
···258302 }
259303 IdentityData::NotFound => {
260304 if (now - *last_fetch) >= MIN_NOT_FOUND_TTL {
305305+ metrics::counter!("identity_handle_refresh_queued", "reason" => "ttl", "found" => "false").increment(1);
261306 self.queue_refresh(key).await;
262307 }
263308 Ok(None)
264309 }
265310 IdentityData::Did(did) => {
266311 if (now - *last_fetch) >= MIN_TTL {
312312+ metrics::counter!("identity_handle_refresh_queued", "reason" => "ttl", "found" => "true").increment(1);
267313 self.queue_refresh(key).await;
268314 }
269315 Ok(Some(did.clone()))
···277323 did: &Did,
278324 ) -> Result<Option<PartialMiniDoc>, IdentityError> {
279325 let key = IdentityKey::Did(did.clone());
326326+ metrics::counter!("slingshot_get_did_doc").increment(1);
280327 let entry = self
281328 .cache
282282- .fetch(key.clone(), {
329329+ .get_or_fetch(&key, {
283330 let did = did.clone();
284331 let resolver = self.did_resolver.clone();
285332 || async move {
286286- match resolver.resolve(&did).await {
287287- Ok(did_doc) => {
333333+ let t0 = Instant::now();
334334+ let (res, success) = match resolver.resolve(&did).await {
335335+ Ok(did_doc) if did_doc.id != did.to_string() => (
288336 // TODO: fix in atrium: should verify id is did
289289- if did_doc.id != did.to_string() {
290290- return Err(foyer::Error::other(Box::new(
291291- IdentityError::BadDidDoc(
292292- "did doc's id did not match did".to_string(),
293293- ),
294294- )));
295295- }
296296- let mini_doc = did_doc.try_into().map_err(|e| {
297297- foyer::Error::Other(Box::new(IdentityError::BadDidDoc(e)))
298298- })?;
299299- Ok(IdentityVal(UtcDateTime::now(), IdentityData::Doc(mini_doc)))
300300- }
301301- Err(atrium_identity::Error::NotFound) => {
302302- Ok(IdentityVal(UtcDateTime::now(), IdentityData::NotFound))
303303- }
304304- Err(other) => Err(foyer::Error::Other(Box::new(
305305- IdentityError::ResolutionFailed(other),
306306- ))),
307307- }
337337+ Err(IdentityError::BadDidDoc(
338338+ "did doc's id did not match did".to_string(),
339339+ )),
340340+ "false",
341341+ ),
342342+ Ok(did_doc) => match did_doc.try_into() {
343343+ Ok(mini_doc) => (
344344+ Ok(IdentityVal(UtcDateTime::now(), IdentityData::Doc(mini_doc))),
345345+ "true",
346346+ ),
347347+ Err(e) => (Err(IdentityError::BadDidDoc(e)), "false"),
348348+ },
349349+ Err(atrium_identity::Error::NotFound) => (
350350+ Ok(IdentityVal(UtcDateTime::now(), IdentityData::NotFound)),
351351+ "false",
352352+ ),
353353+ Err(other) => (Err(IdentityError::ResolutionFailed(other)), "false"),
354354+ };
355355+ metrics::histogram!("slingshot_fetch_did_doc", "success" => success)
356356+ .record(t0.elapsed());
357357+ res
308358 }
309359 })
310360 .await?;
···318368 }
319369 IdentityData::NotFound => {
320370 if (now - *last_fetch) >= MIN_NOT_FOUND_TTL {
371371+ metrics::counter!("identity_did_refresh_queued", "reason" => "ttl", "found" => "false").increment(1);
321372 self.queue_refresh(key).await;
322373 }
323374 Ok(None)
324375 }
325376 IdentityData::Doc(mini_did) => {
326377 if (now - *last_fetch) >= MIN_TTL {
378378+ metrics::counter!("identity_did_refresh_queued", "reason" => "ttl", "found" => "true").increment(1);
327379 self.queue_refresh(key).await;
328380 }
329381 Ok(Some(mini_did.clone()))
···334386 /// put a refresh task on the queue
335387 ///
336388 /// this can be safely called from multiple concurrent tasks
337337- async fn queue_refresh(&self, key: IdentityKey) {
389389+ pub async fn queue_refresh(&self, key: IdentityKey) {
338390 // todo: max queue size
339391 let mut q = self.refresh_queue.lock().await;
340392 if !q.items.contains(&key) {
···411463 /// run the refresh queue consumer
412464 pub async fn run_refresher(&self, shutdown: CancellationToken) -> Result<(), IdentityError> {
413465 let _guard = self
414414- .refresher
466466+ .refresher_task
415467 .try_lock()
416468 .expect("there to only be one refresher running");
417469 loop {
···433485 log::trace!("refreshing handle {handle:?}");
434486 match self.handle_resolver.resolve(handle).await {
435487 Ok(did) => {
488488+ metrics::counter!("identity_handle_refresh", "success" => "true")
489489+ .increment(1);
436490 self.cache.insert(
437491 task_key.clone(),
438492 IdentityVal(UtcDateTime::now(), IdentityData::Did(did)),
439493 );
440494 }
441495 Err(atrium_identity::Error::NotFound) => {
496496+ metrics::counter!("identity_handle_refresh", "success" => "false", "reason" => "not found").increment(1);
442497 self.cache.insert(
443498 task_key.clone(),
444499 IdentityVal(UtcDateTime::now(), IdentityData::NotFound),
445500 );
446501 }
447502 Err(err) => {
503503+ metrics::counter!("identity_handle_refresh", "success" => "false", "reason" => "other").increment(1);
448504 log::warn!(
449505 "failed to refresh handle: {err:?}. leaving stale (should we eventually do something?)"
450506 );
···459515 Ok(did_doc) => {
460516 // TODO: fix in atrium: should verify id is did
461517 if did_doc.id != did.to_string() {
518518+ metrics::counter!("identity_did_refresh", "success" => "false", "reason" => "wrong did").increment(1);
462519 log::warn!(
463520 "refreshed did doc failed: wrong did doc id. dropping refresh."
464521 );
···467524 let mini_doc = match did_doc.try_into() {
468525 Ok(md) => md,
469526 Err(e) => {
527527+ metrics::counter!("identity_did_refresh", "success" => "false", "reason" => "bad doc").increment(1);
470528 log::warn!(
471529 "converting mini doc failed: {e:?}. dropping refresh."
472530 );
473531 continue;
474532 }
475533 };
534534+ metrics::counter!("identity_did_refresh", "success" => "true")
535535+ .increment(1);
476536 self.cache.insert(
477537 task_key.clone(),
478538 IdentityVal(UtcDateTime::now(), IdentityData::Doc(mini_doc)),
479539 );
480540 }
481541 Err(atrium_identity::Error::NotFound) => {
542542+ metrics::counter!("identity_did_refresh", "success" => "false", "reason" => "not found").increment(1);
482543 self.cache.insert(
483544 task_key.clone(),
484545 IdentityVal(UtcDateTime::now(), IdentityData::NotFound),
485546 );
486547 }
487548 Err(err) => {
549549+ metrics::counter!("identity_did_refresh", "success" => "false", "reason" => "other").increment(1);
488550 log::warn!(
489551 "failed to refresh did doc: {err:?}. leaving stale (should we eventually do something?)"
490552 );
+1-1
slingshot/src/lib.rs
···99pub use consumer::consume;
1010pub use firehose_cache::firehose_cache;
1111pub use healthcheck::healthcheck;
1212-pub use identity::Identity;
1212+pub use identity::{Identity, IdentityKey};
1313pub use record::{CachedRecord, ErrorResponseObject, Repo};
1414pub use server::serve;
+86-31
slingshot/src/main.rs
···44use slingshot::{
55 Identity, Repo, consume, error::MainTaskError, firehose_cache, healthcheck, serve,
66};
77+use std::net::SocketAddr;
78use std::path::PathBuf;
89910use clap::Parser;
···1516struct Args {
1617 /// Jetstream server to connect to (exclusive with --fixture). Provide either a wss:// URL, or a shorhand value:
1718 /// 'us-east-1', 'us-east-2', 'us-west-1', or 'us-west-2'
1818- #[arg(long)]
1919+ #[arg(long, env = "SLINGSHOT_JETSTREAM")]
1920 jetstream: String,
2021 /// don't request zstd-compressed jetstream events
2122 ///
2223 /// reduces CPU at the expense of more ingress bandwidth
2323- #[arg(long, action)]
2424+ #[arg(long, action, env = "SLINGSHOT_JETSTREAM_NO_ZSTD")]
2425 jetstream_no_zstd: bool,
2526 /// where to keep disk caches
2626- #[arg(long)]
2727+ #[arg(long, env = "SLINGSHOT_CACHE_DIR")]
2728 cache_dir: PathBuf,
2929+ /// where to listen for incomming requests
3030+ ///
3131+ /// cannot be used with acme -- if you need ipv6 see --acme-ipv6
3232+ #[arg(long, env = "SLINGSHOT_BIND")]
3333+ #[clap(default_value = "0.0.0.0:8080")]
3434+ bind: SocketAddr,
3535+ /// memory cache size in megabytes for records
3636+ #[arg(long, env = "SLINGSHOT_RECORD_CACHE_MEMORY_MB")]
3737+ #[clap(default_value_t = 64)]
3838+ record_cache_memory_mb: usize,
3939+ /// disk cache size in gigabytes for records
4040+ #[arg(long, env = "SLINGSHOT_RECORD_CACHE_DISK_DB")]
4141+ #[clap(default_value_t = 1)]
4242+ record_cache_disk_gb: usize,
4343+ /// memory cache size in megabytes for identities
4444+ #[arg(long, env = "SLINGSHOT_IDENTITY_CACHE_MEMORY_MB")]
4545+ #[clap(default_value_t = 64)]
4646+ identity_cache_memory_mb: usize,
4747+ /// disk cache size in gigabytes for identities
4848+ #[arg(long, env = "SLINGSHOT_IDENTITY_CACHE_DISK_DB")]
4949+ #[clap(default_value_t = 1)]
5050+ identity_cache_disk_gb: usize,
2851 /// the domain pointing to this server
2952 ///
3053 /// if present:
3154 /// - a did:web document will be served at /.well-known/did.json
3255 /// - an HTTPS certs will be automatically configured with Acme/letsencrypt
3356 /// - TODO: a rate-limiter will be installed
3434- #[arg(long)]
3535- domain: Option<String>,
5757+ #[arg(
5858+ long,
5959+ conflicts_with("bind"),
6060+ requires("acme_cache_path"),
6161+ env = "SLINGSHOT_ACME_DOMAIN"
6262+ )]
6363+ acme_domain: Option<String>,
3664 /// email address for letsencrypt contact
3765 ///
3866 /// recommended in production, i guess?
3939- #[arg(long)]
6767+ #[arg(long, requires("acme_domain"), env = "SLINGSHOT_ACME_CONTACT")]
4068 acme_contact: Option<String>,
4169 /// a location to cache acme https certs
4270 ///
4343- /// only used if --host is specified. omitting requires re-requesting certs
4444- /// on every restart, and letsencrypt has rate limits that are easy to hit.
7171+ /// required when (and only used when) --acme-domain is specified.
4572 ///
4673 /// recommended in production, but mind the file permissions.
4747- #[arg(long)]
4848- certs: Option<PathBuf>,
7474+ #[arg(long, requires("acme_domain"), env = "SLINGSHOT_ACME_CACHE_PATH")]
7575+ acme_cache_path: Option<PathBuf>,
7676+ /// listen for ipv6 when using acme
7777+ ///
7878+ /// you must also configure the relevant DNS records for this to work
7979+ #[arg(long, action, requires("acme_domain"), env = "SLINGSHOT_ACME_IPV6")]
8080+ acme_ipv6: bool,
4981 /// an web address to send healtcheck pings to every ~51s or so
5050- #[arg(long)]
8282+ #[arg(long, env = "SLINGSHOT_HEALTHCHECK")]
5183 healthcheck: Option<String>,
8484+ /// enable metrics collection and serving
8585+ #[arg(long, action, env = "SLINGSHOT_COLLECT_METRICS")]
8686+ collect_metrics: bool,
8787+ /// metrics server's listen address
8888+ #[arg(long, requires("collect_metrics"), env = "SLINGSHOT_BIND_METRICS")]
8989+ #[clap(default_value = "[::]:8765")]
9090+ bind_metrics: std::net::SocketAddr,
5291}
53925493#[tokio::main]
···6210163102 let args = Args::parse();
641036565- if let Err(e) = install_metrics_server() {
6666- log::error!("failed to install metrics server: {e:?}");
6767- } else {
6868- log::info!("metrics listening at http://0.0.0.0:8765");
104104+ if args.collect_metrics {
105105+ log::trace!("installing metrics server...");
106106+ if let Err(e) = install_metrics_server(args.bind_metrics) {
107107+ log::error!("failed to install metrics server: {e:?}");
108108+ } else {
109109+ log::info!("metrics listening at http://{}", args.bind_metrics);
110110+ }
69111 }
7011271113 std::fs::create_dir_all(&args.cache_dir).map_err(|e| {
···83125 log::info!("cache dir ready at at {cache_dir:?}.");
8412685127 log::info!("setting up firehose cache...");
8686- let cache = firehose_cache(cache_dir.join("./firehose")).await?;
128128+ let cache = firehose_cache(
129129+ cache_dir.join("./firehose"),
130130+ args.record_cache_memory_mb,
131131+ args.record_cache_disk_gb,
132132+ )
133133+ .await?;
87134 log::info!("firehose cache ready.");
8813589136 let mut tasks: tokio::task::JoinSet<Result<(), MainTaskError>> = tokio::task::JoinSet::new();
9013791138 log::info!("starting identity service...");
9292- let identity = Identity::new(cache_dir.join("./identity"))
9393- .await
9494- .map_err(|e| format!("identity setup failed: {e:?}"))?;
139139+ let identity = Identity::new(
140140+ cache_dir.join("./identity"),
141141+ args.identity_cache_memory_mb,
142142+ args.identity_cache_disk_gb,
143143+ )
144144+ .await
145145+ .map_err(|e| format!("identity setup failed: {e:?}"))?;
146146+95147 log::info!("identity service ready.");
96148 let identity_refresher = identity.clone();
97149 let identity_shutdown = shutdown.clone();
···102154103155 let repo = Repo::new(identity.clone());
104156157157+ let identity_for_server = identity.clone();
105158 let server_shutdown = shutdown.clone();
106159 let server_cache_handle = cache.clone();
160160+ let bind = args.bind;
107161 tasks.spawn(async move {
108162 serve(
109163 server_cache_handle,
110110- identity,
164164+ identity_for_server,
111165 repo,
112112- args.domain,
166166+ args.acme_domain,
113167 args.acme_contact,
114114- args.certs,
168168+ args.acme_cache_path,
169169+ args.acme_ipv6,
115170 server_shutdown,
171171+ bind,
116172 )
117173 .await?;
118174 Ok(())
119175 });
120176177177+ let identity_refreshable = identity.clone();
121178 let consumer_shutdown = shutdown.clone();
122179 let consumer_cache = cache.clone();
123180 tasks.spawn(async move {
···125182 args.jetstream,
126183 None,
127184 args.jetstream_no_zstd,
185185+ identity_refreshable,
128186 consumer_shutdown,
129187 consumer_cache,
130188 )
···172230 Ok(())
173231}
174232175175-fn install_metrics_server() -> Result<(), metrics_exporter_prometheus::BuildError> {
233233+fn install_metrics_server(
234234+ bind_metrics: std::net::SocketAddr,
235235+) -> Result<(), metrics_exporter_prometheus::BuildError> {
176236 log::info!("installing metrics server...");
177177- let host = [0, 0, 0, 0];
178178- let port = 8765;
179237 PrometheusBuilder::new()
180238 .set_quantiles(&[0.5, 0.9, 0.99, 1.0])?
181239 .set_bucket_duration(std::time::Duration::from_secs(300))?
182240 .set_bucket_count(std::num::NonZero::new(12).unwrap()) // count * duration = 60 mins. stuff doesn't happen that fast here.
183241 .set_enable_unit_suffix(false) // this seemed buggy for constellation (sometimes wouldn't engage)
184184- .with_http_listener((host, port))
242242+ .with_http_listener(bind_metrics)
185243 .install()?;
186244 log::info!(
187187- "metrics server installed! listening on http://{}.{}.{}.{}:{port}",
188188- host[0],
189189- host[1],
190190- host[2],
191191- host[3]
245245+ "metrics server installed! listening on http://{}",
246246+ bind_metrics
192247 );
193248 Ok(())
194249}
···11+ Apache License
22+ Version 2.0, January 2004
33+ http://www.apache.org/licenses/
44+55+TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
66+77+1. Definitions.
88+99+ "License" shall mean the terms and conditions for use, reproduction,
1010+ and distribution as defined by Sections 1 through 9 of this document.
1111+1212+ "Licensor" shall mean the copyright owner or entity authorized by
1313+ the copyright owner that is granting the License.
1414+1515+ "Legal Entity" shall mean the union of the acting entity and all
1616+ other entities that control, are controlled by, or are under common
1717+ control with that entity. For the purposes of this definition,
1818+ "control" means (i) the power, direct or indirect, to cause the
1919+ direction or management of such entity, whether by contract or
2020+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
2121+ outstanding shares, or (iii) beneficial ownership of such entity.
2222+2323+ "You" (or "Your") shall mean an individual or Legal Entity
2424+ exercising permissions granted by this License.
2525+2626+ "Source" form shall mean the preferred form for making modifications,
2727+ including but not limited to software source code, documentation
2828+ source, and configuration files.
2929+3030+ "Object" form shall mean any form resulting from mechanical
3131+ transformation or translation of a Source form, including but
3232+ not limited to compiled object code, generated documentation,
3333+ and conversions to other media types.
3434+3535+ "Work" shall mean the work of authorship, whether in Source or
3636+ Object form, made available under the License, as indicated by a
3737+ copyright notice that is included in or attached to the work
3838+ (an example is provided in the Appendix below).
3939+4040+ "Derivative Works" shall mean any work, whether in Source or Object
4141+ form, that is based on (or derived from) the Work and for which the
4242+ editorial revisions, annotations, elaborations, or other modifications
4343+ represent, as a whole, an original work of authorship. For the purposes
4444+ of this License, Derivative Works shall not include works that remain
4545+ separable from, or merely link (or bind by name) to the interfaces of,
4646+ the Work and Derivative Works thereof.
4747+4848+ "Contribution" shall mean any work of authorship, including
4949+ the original version of the Work and any modifications or additions
5050+ to that Work or Derivative Works thereof, that is intentionally
5151+ submitted to Licensor for inclusion in the Work by the copyright owner
5252+ or by an individual or Legal Entity authorized to submit on behalf of
5353+ the copyright owner. For the purposes of this definition, "submitted"
5454+ means any form of electronic, verbal, or written communication sent
5555+ to the Licensor or its representatives, including but not limited to
5656+ communication on electronic mailing lists, source code control systems,
5757+ and issue tracking systems that are managed by, or on behalf of, the
5858+ Licensor for the purpose of discussing and improving the Work, but
5959+ excluding communication that is conspicuously marked or otherwise
6060+ designated in writing by the copyright owner as "Not a Contribution."
6161+6262+ "Contributor" shall mean Licensor and any individual or Legal Entity
6363+ on behalf of whom a Contribution has been received by Licensor and
6464+ subsequently incorporated within the Work.
6565+6666+2. Grant of Copyright License. Subject to the terms and conditions of
6767+ this License, each Contributor hereby grants to You a perpetual,
6868+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
6969+ copyright license to reproduce, prepare Derivative Works of,
7070+ publicly display, publicly perform, sublicense, and distribute the
7171+ Work and such Derivative Works in Source or Object form.
7272+7373+3. Grant of Patent License. Subject to the terms and conditions of
7474+ this License, each Contributor hereby grants to You a perpetual,
7575+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
7676+ (except as stated in this section) patent license to make, have made,
7777+ use, offer to sell, sell, import, and otherwise transfer the Work,
7878+ where such license applies only to those patent claims licensable
7979+ by such Contributor that are necessarily infringed by their
8080+ Contribution(s) alone or by combination of their Contribution(s)
8181+ with the Work to which such Contribution(s) was submitted. If You
8282+ institute patent litigation against any entity (including a
8383+ cross-claim or counterclaim in a lawsuit) alleging that the Work
8484+ or a Contribution incorporated within the Work constitutes direct
8585+ or contributory patent infringement, then any patent licenses
8686+ granted to You under this License for that Work shall terminate
8787+ as of the date such litigation is filed.
8888+8989+4. Redistribution. You may reproduce and distribute copies of the
9090+ Work or Derivative Works thereof in any medium, with or without
9191+ modifications, and in Source or Object form, provided that You
9292+ meet the following conditions:
9393+9494+ (a) You must give any other recipients of the Work or
9595+ Derivative Works a copy of this License; and
9696+9797+ (b) You must cause any modified files to carry prominent notices
9898+ stating that You changed the files; and
9999+100100+ (c) You must retain, in the Source form of any Derivative Works
101101+ that You distribute, all copyright, patent, trademark, and
102102+ attribution notices from the Source form of the Work,
103103+ excluding those notices that do not pertain to any part of
104104+ the Derivative Works; and
105105+106106+ (d) If the Work includes a "NOTICE" text file as part of its
107107+ distribution, then any Derivative Works that You distribute must
108108+ include a readable copy of the attribution notices contained
109109+ within such NOTICE file, excluding those notices that do not
110110+ pertain to any part of the Derivative Works, in at least one
111111+ of the following places: within a NOTICE text file distributed
112112+ as part of the Derivative Works; within the Source form or
113113+ documentation, if provided along with the Derivative Works; or,
114114+ within a display generated by the Derivative Works, if and
115115+ wherever such third-party notices normally appear. The contents
116116+ of the NOTICE file are for informational purposes only and
117117+ do not modify the License. You may add Your own attribution
118118+ notices within Derivative Works that You distribute, alongside
119119+ or as an addendum to the NOTICE text from the Work, provided
120120+ that such additional attribution notices cannot be construed
121121+ as modifying the License.
122122+123123+ You may add Your own copyright statement to Your modifications and
124124+ may provide additional or different license terms and conditions
125125+ for use, reproduction, or distribution of Your modifications, or
126126+ for any such Derivative Works as a whole, provided Your use,
127127+ reproduction, and distribution of the Work otherwise complies with
128128+ the conditions stated in this License.
129129+130130+5. Submission of Contributions. Unless You explicitly state otherwise,
131131+ any Contribution intentionally submitted for inclusion in the Work
132132+ by You to the Licensor shall be under the terms and conditions of
133133+ this License, without any additional terms or conditions.
134134+ Notwithstanding the above, nothing herein shall supersede or modify
135135+ the terms of any separate license agreement you may have executed
136136+ with Licensor regarding such Contributions.
137137+138138+6. Trademarks. This License does not grant permission to use the trade
139139+ names, trademarks, service marks, or product names of the Licensor,
140140+ except as required for reasonable and customary use in describing the
141141+ origin of the Work and reproducing the content of the NOTICE file.
142142+143143+7. Disclaimer of Warranty. Unless required by applicable law or
144144+ agreed to in writing, Licensor provides the Work (and each
145145+ Contributor provides its Contributions) on an "AS IS" BASIS,
146146+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147147+ implied, including, without limitation, any warranties or conditions
148148+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149149+ PARTICULAR PURPOSE. You are solely responsible for determining the
150150+ appropriateness of using or redistributing the Work and assume any
151151+ risks associated with Your exercise of permissions under this License.
152152+153153+8. Limitation of Liability. In no event and under no legal theory,
154154+ whether in tort (including negligence), contract, or otherwise,
155155+ unless required by applicable law (such as deliberate and grossly
156156+ negligent acts) or agreed to in writing, shall any Contributor be
157157+ liable to You for damages, including any direct, indirect, special,
158158+ incidental, or consequential damages of any character arising as a
159159+ result of this License or out of the use or inability to use the
160160+ Work (including but not limited to damages for loss of goodwill,
161161+ work stoppage, computer failure or malfunction, or any and all
162162+ other commercial damages or losses), even if such Contributor
163163+ has been advised of the possibility of such damages.
164164+165165+9. Accepting Warranty or Additional Liability. While redistributing
166166+ the Work or Derivative Works thereof, You may choose to offer,
167167+ and charge a fee for, acceptance of support, warranty, indemnity,
168168+ or other liability obligations and/or rights consistent with this
169169+ License. However, in accepting such obligations, You may act only
170170+ on Your own behalf and on Your sole responsibility, not on behalf
171171+ of any other Contributor, and only if You agree to indemnify,
172172+ defend, and hold each Contributor harmless for any liability
173173+ incurred by, or claims asserted against, such Contributor by reason
174174+ of your accepting any such warranty or additional liability.
175175+176176+END OF TERMS AND CONDITIONS
177177+178178+Copyright 2025 microcosm
179179+180180+Licensed under the Apache License, Version 2.0 (the "License");
181181+you may not use this file except in compliance with the License.
182182+You may obtain a copy of the License at
183183+184184+ http://www.apache.org/licenses/LICENSE-2.0
185185+186186+Unless required by applicable law or agreed to in writing, software
187187+distributed under the License is distributed on an "AS IS" BASIS,
188188+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
189189+See the License for the specific language governing permissions and
190190+limitations under the License.
+21
spacedust/LICENSE.MIT
···11+MIT License
22+33+Copyright (c) 2025 microcosm
44+55+Permission is hereby granted, free of charge, to any person obtaining a copy
66+of this software and associated documentation files (the "Software"), to deal
77+in the Software without restriction, including without limitation the rights
88+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
99+copies of the Software, and to permit persons to whom the Software is
1010+furnished to do so, subject to the following conditions:
1111+1212+The above copyright notice and this permission notice shall be included in all
1313+copies or substantial portions of the Software.
1414+1515+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
1616+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
1717+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
1818+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
1919+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
2020+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
2121+SOFTWARE.
+18
spacedust/readme.md
···11+# spacedust
22+33+links firehose
44+55+fyi: the current verison of spacedust is very lightweight, but also limited: it offers no replay window, and cannot emit delete events since it doesn't retain any history.
66+77+(it does offer link filtering by link subject (aka backlinks!) which is still pretty neat)
88+99+the next version of spacedust will be quite a large overhaul: a complete forward-link index with full-network replay and hydrated deletes. it won't be lightweight anymore but it's going to be a lot more powerful.
1010+1111+currently since there are a few spacedust consumers out there, and since it's so lightweight and stable, i'm planning to keep the existing version running on its pi4 host machine indefinitely.
1212+1313+1414+## license
1515+1616+This work is dual-licensed under MIT and Apache 2.0. You can choose between one of them if you use this work.
1717+1818+`SPDX-License-Identifier: MIT OR Apache-2.0`
···1616struct Args {
1717 /// Jetstream server to connect to (exclusive with --fixture). Provide either a wss:// URL, or a shorhand value:
1818 /// 'us-east-1', 'us-east-2', 'us-west-1', or 'us-west-2'
1919- #[arg(long)]
1919+ #[arg(long, env = "SPACEDUST_JETSTREAM")]
2020 jetstream: String,
2121 /// don't request zstd-compressed jetstream events
2222 ///
2323 /// reduces CPU at the expense of more ingress bandwidth
2424- #[arg(long, action)]
2424+ #[arg(long, action, env = "SPACEDUST_JETSTREAM_NO_ZSTD")]
2525 jetstream_no_zstd: bool,
2626+ /// spacedust server's listen address
2727+ #[arg(long, env = "SPACEDUST_BIND")]
2828+ #[clap(default_value = "[::]:8080")]
2929+ bind: std::net::SocketAddr,
3030+ /// enable metrics collection and serving
3131+ #[arg(long, action, env = "SPACEDUST_COLLECT_METRICS")]
3232+ collect_metrics: bool,
3333+ /// metrics server's listen address
3434+ #[arg(long, requires("collect_metrics"), env = "SPACEDUST_BIND_METRICS")]
3535+ #[clap(default_value = "[::]:8765")]
3636+ bind_metrics: std::net::SocketAddr,
2637}
27382839#[tokio::main]
···60716172 let args = Args::parse();
62736363- if let Err(e) = install_metrics_server() {
6464- log::error!("failed to install metrics server: {e:?}");
6565- };
7474+ if args.collect_metrics {
7575+ log::trace!("installing metrics server...");
7676+ if let Err(e) = install_metrics_server(args.bind_metrics) {
7777+ log::error!("failed to install metrics server: {e:?}");
7878+ };
7979+ }
66806781 let mut tasks: tokio::task::JoinSet<Result<(), MainTaskError>> = tokio::task::JoinSet::new();
68826983 let server_shutdown = shutdown.clone();
8484+ let bind = args.bind;
7085 tasks.spawn(async move {
7171- server::serve(b, d, server_shutdown).await?;
8686+ server::serve(b, d, server_shutdown, bind).await?;
7287 Ok(())
7388 });
7489···122137 Ok(())
123138}
124139125125-fn install_metrics_server() -> Result<(), metrics_exporter_prometheus::BuildError> {
140140+fn install_metrics_server(
141141+ bind: std::net::SocketAddr,
142142+) -> Result<(), metrics_exporter_prometheus::BuildError> {
126143 log::info!("installing metrics server...");
127127- let host = [0, 0, 0, 0];
128128- let port = 8765;
129144 PrometheusBuilder::new()
130145 .set_quantiles(&[0.5, 0.9, 0.99, 1.0])?
131146 .set_bucket_duration(std::time::Duration::from_secs(300))?
132147 .set_bucket_count(std::num::NonZero::new(12).unwrap()) // count * duration = 60 mins. stuff doesn't happen that fast here.
133148 .set_enable_unit_suffix(false) // this seemed buggy for constellation (sometimes wouldn't engage)
134134- .with_http_listener((host, port))
149149+ .with_http_listener(bind)
135150 .install()?;
136136- log::info!(
137137- "metrics server installed! listening on http://{}.{}.{}.{}:{port}",
138138- host[0],
139139- host[1],
140140- host[2],
141141- host[3]
142142- );
151151+ log::info!("metrics server installed! listening on {bind}");
143152 Ok(())
144153}
+13-3
spacedust/src/server.rs
···2929 b: broadcast::Sender<Arc<ClientMessage>>,
3030 d: broadcast::Sender<Arc<ClientMessage>>,
3131 shutdown: CancellationToken,
3232+ bind: std::net::SocketAddr,
3233) -> Result<(), ServerError> {
3334 let config_logging = ConfigLogging::StderrTerminal {
3435 level: ConfigLoggingLevel::Info,
···72737374 let server = ServerBuilder::new(api, ctx, log)
7475 .config(ConfigDropshot {
7575- bind_address: "0.0.0.0:9998".parse().unwrap(),
7676+ bind_address: bind,
7677 ..Default::default()
7778 })
7879 .start()?;
···227228 #[serde(default)]
228229 pub wanted_subjects: HashSet<String>,
229230 #[serde(default)]
231231+ pub wanted_subject_prefixes: HashSet<String>,
232232+ #[serde(default)]
230233 pub wanted_subject_dids: HashSet<String>,
231234 #[serde(default)]
232235 pub wanted_sources: HashSet<String>,
···241244 ///
242245 /// The at-uri must be url-encoded
243246 ///
244244- /// Pass this parameter multiple times to specify multiple collections, like
247247+ /// Pass this parameter multiple times to specify multiple subjects, like
245248 /// `wantedSubjects=[...]&wantedSubjects=[...]`
246249 pub wanted_subjects: String,
250250+ /// One or more at-uri, URI, or DID prefixes to receive links about
251251+ ///
252252+ /// The uri must be url-encoded
253253+ ///
254254+ /// Pass this parameter multiple times to specify multiple prefixes, like
255255+ /// `wantedSubjectPrefixes=[...]&wantedSubjectPrefixes=[...]`
256256+ pub wanted_subject_prefixes: String,
247257 /// One or more DIDs to receive links about
248258 ///
249249- /// Pass this parameter multiple times to specify multiple collections
259259+ /// Pass this parameter multiple times to specify multiple subjects
250260 pub wanted_subject_dids: String,
251261 /// One or more link sources to receive links about
252262 ///
+15-6
spacedust/src/subscriber.rs
···4242 loop {
4343 tokio::select! {
4444 l = receiver.recv() => match l {
4545- Ok(link) => if self.filter(&link.properties) {
4646- if let Err(e) = ws_sender.send(link.message.clone()).await {
4747- log::warn!("failed to send link, dropping subscriber: {e:?}");
4848- break;
4949- }
4545+ Ok(link) => if self.filter(&link.properties)
4646+ && let Err(e) = ws_sender.send(link.message.clone()).await
4747+ {
4848+ log::warn!("failed to send link, dropping subscriber: {e:?}");
4949+ break;
5050 },
5151 Err(RecvError::Closed) => self.shutdown.cancel(),
5252 Err(RecvError::Lagged(n)) => {
···124124 let query = &self.query;
125125126126 // subject + subject DIDs are logical OR
127127- if !(query.wanted_subjects.is_empty() && query.wanted_subject_dids.is_empty()
127127+ if !(query.wanted_subjects.is_empty()
128128+ && query.wanted_subject_prefixes.is_empty()
129129+ && query.wanted_subject_dids.is_empty()
128130 || query.wanted_subjects.contains(&properties.subject)
131131+ || query
132132+ .wanted_subject_prefixes
133133+ .iter()
134134+ .any(|p| properties.subject.starts_with(p))
129135 || properties
130136 .subject_did
131137 .as_ref()
···154160 }
155161 if opts.wanted_subject_dids.len() > 10_000 {
156162 return Err(SubscriberUpdateError::TooManyDidsWanted);
163163+ }
164164+ if opts.wanted_subject_prefixes.len() > 100 {
165165+ return Err(SubscriberUpdateError::TooManySubjectPrefixesWanted);
157166 }
158167 if opts.wanted_subjects.len() > 50_000 {
159168 return Err(SubscriberUpdateError::TooManySubjectsWanted);
+7-3
ufos/Cargo.toml
···88async-trait = "0.1.88"
99base64 = "0.22.1"
1010bincode = { version = "2.0.1", features = ["serde"] }
1111-cardinality-estimator-safe = { version = "4.0.2", features = ["with_serde", "with_digest"] }
1111+cardinality-estimator-safe = { version = "4.0.3", features = ["with_serde", "with_digest"] }
1212chrono = { version = "0.4.41", features = ["serde"] }
1313-clap = { version = "4.5.31", features = ["derive"] }
1313+clap = { workspace = true }
1414dropshot = "0.16.0"
1515env_logger = "0.11.7"
1616-fjall = { git = "https://github.com/fjall-rs/fjall.git", features = ["lz4"] }
1616+fjall = { git = "https://github.com/fjall-rs/fjall.git", rev = "fb229572bb7d1d6966a596994dc1708e47ec57d8", features = ["lz4"] }
1717getrandom = "0.3.3"
1818http = "1.3.1"
1919jetstream = { path = "../jetstream", features = ["metrics"] }
···33333434[target.'cfg(not(target_env = "msvc"))'.dependencies]
3535tikv-jemallocator = "0.6.0"
3636+3737+[[bin]]
3838+name = "analyze"
3939+path = "src/bin/analyze.rs"
36403741[dev-dependencies]
3842tempfile = "3.19.1"
+190
ufos/LICENSE.Apache-2.0
···11+ Apache License
22+ Version 2.0, January 2004
33+ http://www.apache.org/licenses/
44+55+TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
66+77+1. Definitions.
88+99+ "License" shall mean the terms and conditions for use, reproduction,
1010+ and distribution as defined by Sections 1 through 9 of this document.
1111+1212+ "Licensor" shall mean the copyright owner or entity authorized by
1313+ the copyright owner that is granting the License.
1414+1515+ "Legal Entity" shall mean the union of the acting entity and all
1616+ other entities that control, are controlled by, or are under common
1717+ control with that entity. For the purposes of this definition,
1818+ "control" means (i) the power, direct or indirect, to cause the
1919+ direction or management of such entity, whether by contract or
2020+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
2121+ outstanding shares, or (iii) beneficial ownership of such entity.
2222+2323+ "You" (or "Your") shall mean an individual or Legal Entity
2424+ exercising permissions granted by this License.
2525+2626+ "Source" form shall mean the preferred form for making modifications,
2727+ including but not limited to software source code, documentation
2828+ source, and configuration files.
2929+3030+ "Object" form shall mean any form resulting from mechanical
3131+ transformation or translation of a Source form, including but
3232+ not limited to compiled object code, generated documentation,
3333+ and conversions to other media types.
3434+3535+ "Work" shall mean the work of authorship, whether in Source or
3636+ Object form, made available under the License, as indicated by a
3737+ copyright notice that is included in or attached to the work
3838+ (an example is provided in the Appendix below).
3939+4040+ "Derivative Works" shall mean any work, whether in Source or Object
4141+ form, that is based on (or derived from) the Work and for which the
4242+ editorial revisions, annotations, elaborations, or other modifications
4343+ represent, as a whole, an original work of authorship. For the purposes
4444+ of this License, Derivative Works shall not include works that remain
4545+ separable from, or merely link (or bind by name) to the interfaces of,
4646+ the Work and Derivative Works thereof.
4747+4848+ "Contribution" shall mean any work of authorship, including
4949+ the original version of the Work and any modifications or additions
5050+ to that Work or Derivative Works thereof, that is intentionally
5151+ submitted to Licensor for inclusion in the Work by the copyright owner
5252+ or by an individual or Legal Entity authorized to submit on behalf of
5353+ the copyright owner. For the purposes of this definition, "submitted"
5454+ means any form of electronic, verbal, or written communication sent
5555+ to the Licensor or its representatives, including but not limited to
5656+ communication on electronic mailing lists, source code control systems,
5757+ and issue tracking systems that are managed by, or on behalf of, the
5858+ Licensor for the purpose of discussing and improving the Work, but
5959+ excluding communication that is conspicuously marked or otherwise
6060+ designated in writing by the copyright owner as "Not a Contribution."
6161+6262+ "Contributor" shall mean Licensor and any individual or Legal Entity
6363+ on behalf of whom a Contribution has been received by Licensor and
6464+ subsequently incorporated within the Work.
6565+6666+2. Grant of Copyright License. Subject to the terms and conditions of
6767+ this License, each Contributor hereby grants to You a perpetual,
6868+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
6969+ copyright license to reproduce, prepare Derivative Works of,
7070+ publicly display, publicly perform, sublicense, and distribute the
7171+ Work and such Derivative Works in Source or Object form.
7272+7373+3. Grant of Patent License. Subject to the terms and conditions of
7474+ this License, each Contributor hereby grants to You a perpetual,
7575+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
7676+ (except as stated in this section) patent license to make, have made,
7777+ use, offer to sell, sell, import, and otherwise transfer the Work,
7878+ where such license applies only to those patent claims licensable
7979+ by such Contributor that are necessarily infringed by their
8080+ Contribution(s) alone or by combination of their Contribution(s)
8181+ with the Work to which such Contribution(s) was submitted. If You
8282+ institute patent litigation against any entity (including a
8383+ cross-claim or counterclaim in a lawsuit) alleging that the Work
8484+ or a Contribution incorporated within the Work constitutes direct
8585+ or contributory patent infringement, then any patent licenses
8686+ granted to You under this License for that Work shall terminate
8787+ as of the date such litigation is filed.
8888+8989+4. Redistribution. You may reproduce and distribute copies of the
9090+ Work or Derivative Works thereof in any medium, with or without
9191+ modifications, and in Source or Object form, provided that You
9292+ meet the following conditions:
9393+9494+ (a) You must give any other recipients of the Work or
9595+ Derivative Works a copy of this License; and
9696+9797+ (b) You must cause any modified files to carry prominent notices
9898+ stating that You changed the files; and
9999+100100+ (c) You must retain, in the Source form of any Derivative Works
101101+ that You distribute, all copyright, patent, trademark, and
102102+ attribution notices from the Source form of the Work,
103103+ excluding those notices that do not pertain to any part of
104104+ the Derivative Works; and
105105+106106+ (d) If the Work includes a "NOTICE" text file as part of its
107107+ distribution, then any Derivative Works that You distribute must
108108+ include a readable copy of the attribution notices contained
109109+ within such NOTICE file, excluding those notices that do not
110110+ pertain to any part of the Derivative Works, in at least one
111111+ of the following places: within a NOTICE text file distributed
112112+ as part of the Derivative Works; within the Source form or
113113+ documentation, if provided along with the Derivative Works; or,
114114+ within a display generated by the Derivative Works, if and
115115+ wherever such third-party notices normally appear. The contents
116116+ of the NOTICE file are for informational purposes only and
117117+ do not modify the License. You may add Your own attribution
118118+ notices within Derivative Works that You distribute, alongside
119119+ or as an addendum to the NOTICE text from the Work, provided
120120+ that such additional attribution notices cannot be construed
121121+ as modifying the License.
122122+123123+ You may add Your own copyright statement to Your modifications and
124124+ may provide additional or different license terms and conditions
125125+ for use, reproduction, or distribution of Your modifications, or
126126+ for any such Derivative Works as a whole, provided Your use,
127127+ reproduction, and distribution of the Work otherwise complies with
128128+ the conditions stated in this License.
129129+130130+5. Submission of Contributions. Unless You explicitly state otherwise,
131131+ any Contribution intentionally submitted for inclusion in the Work
132132+ by You to the Licensor shall be under the terms and conditions of
133133+ this License, without any additional terms or conditions.
134134+ Notwithstanding the above, nothing herein shall supersede or modify
135135+ the terms of any separate license agreement you may have executed
136136+ with Licensor regarding such Contributions.
137137+138138+6. Trademarks. This License does not grant permission to use the trade
139139+ names, trademarks, service marks, or product names of the Licensor,
140140+ except as required for reasonable and customary use in describing the
141141+ origin of the Work and reproducing the content of the NOTICE file.
142142+143143+7. Disclaimer of Warranty. Unless required by applicable law or
144144+ agreed to in writing, Licensor provides the Work (and each
145145+ Contributor provides its Contributions) on an "AS IS" BASIS,
146146+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147147+ implied, including, without limitation, any warranties or conditions
148148+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149149+ PARTICULAR PURPOSE. You are solely responsible for determining the
150150+ appropriateness of using or redistributing the Work and assume any
151151+ risks associated with Your exercise of permissions under this License.
152152+153153+8. Limitation of Liability. In no event and under no legal theory,
154154+ whether in tort (including negligence), contract, or otherwise,
155155+ unless required by applicable law (such as deliberate and grossly
156156+ negligent acts) or agreed to in writing, shall any Contributor be
157157+ liable to You for damages, including any direct, indirect, special,
158158+ incidental, or consequential damages of any character arising as a
159159+ result of this License or out of the use or inability to use the
160160+ Work (including but not limited to damages for loss of goodwill,
161161+ work stoppage, computer failure or malfunction, or any and all
162162+ other commercial damages or losses), even if such Contributor
163163+ has been advised of the possibility of such damages.
164164+165165+9. Accepting Warranty or Additional Liability. While redistributing
166166+ the Work or Derivative Works thereof, You may choose to offer,
167167+ and charge a fee for, acceptance of support, warranty, indemnity,
168168+ or other liability obligations and/or rights consistent with this
169169+ License. However, in accepting such obligations, You may act only
170170+ on Your own behalf and on Your sole responsibility, not on behalf
171171+ of any other Contributor, and only if You agree to indemnify,
172172+ defend, and hold each Contributor harmless for any liability
173173+ incurred by, or claims asserted against, such Contributor by reason
174174+ of your accepting any such warranty or additional liability.
175175+176176+END OF TERMS AND CONDITIONS
177177+178178+Copyright 2025 microcosm
179179+180180+Licensed under the Apache License, Version 2.0 (the "License");
181181+you may not use this file except in compliance with the License.
182182+You may obtain a copy of the License at
183183+184184+ http://www.apache.org/licenses/LICENSE-2.0
185185+186186+Unless required by applicable law or agreed to in writing, software
187187+distributed under the License is distributed on an "AS IS" BASIS,
188188+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
189189+See the License for the specific language governing permissions and
190190+limitations under the License.
+21
ufos/LICENSE.MIT
···11+MIT License
22+33+Copyright (c) 2025 microcosm
44+55+Permission is hereby granted, free of charge, to any person obtaining a copy
66+of this software and associated documentation files (the "Software"), to deal
77+in the Software without restriction, including without limitation the rights
88+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
99+copies of the Software, and to permit persons to whom the Software is
1010+furnished to do so, subject to the following conditions:
1111+1212+The above copyright notice and this permission notice shall be included in all
1313+copies or substantial portions of the Software.
1414+1515+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
1616+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
1717+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
1818+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
1919+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
2020+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
2121+SOFTWARE.
+7
ufos/readme.md
···150150```
151151152152to fuzz the counts value things
153153+154154+155155+## license
156156+157157+This work is dual-licensed under MIT and Apache 2.0. You can choose between one of them if you use this work.
158158+159159+`SPDX-License-Identifier: MIT OR Apache-2.0`
+170
ufos/src/bin/analyze.rs
···11+use cardinality_estimator_safe::Sketch;
22+use chrono::{DateTime, Utc};
33+use clap::{Parser, Subcommand};
44+use fjall::{Config, PartitionCreateOptions, PartitionHandle};
55+use std::collections::BTreeMap;
66+use std::path::PathBuf;
77+use ufos::db_types::{db_complete, DbBytes};
88+use ufos::store_types::{
99+ AllTimeRollupKey, AllTimeRollupStaticPrefix, CountsValue, WeekTruncatedCursor, WeeklyRollupKey,
1010+ WeeklyRollupStaticPrefix, WithCollection,
1111+};
1212+1313+#[derive(Parser)]
1414+#[command(about = "One-off data analysis of ufos rollup data")]
1515+struct Cli {
1616+ /// Path to the fjall data directory
1717+ data: PathBuf,
1818+ #[command(subcommand)]
1919+ command: Command,
2020+}
2121+2222+#[derive(Subcommand)]
2323+enum Command {
2424+ /// Total estimated distinct users across all time and every group
2525+ TotalUsers,
2626+ /// Weekly estimated distinct users (excluding app.bsky.*/chat.bsky.*)
2727+ WeeklyUsers,
2828+ /// Weekly count of groups with >10 estimated distinct users (excluding app.bsky.*/chat.bsky.*)
2929+ WeeklyGroups,
3030+ /// Like weekly-groups but with the last NSID segment removed
3131+ WeeklyParents,
3232+}
3333+3434+fn week_label(week: WeekTruncatedCursor) -> String {
3535+ let us = week.to_raw_u64();
3636+ let secs = (us / 1_000_000) as i64;
3737+ let dt = DateTime::<Utc>::from_timestamp(secs, 0).unwrap();
3838+ dt.format("%Y-%m-%d").to_string()
3939+}
4040+4141+fn is_excluded(nsid: &str) -> bool {
4242+ nsid.starts_with("app.bsky.") || nsid.starts_with("chat.bsky.")
4343+}
4444+4545+fn parent_prefix(nsid: &str) -> &str {
4646+ let Some((pre, _)) = nsid.rsplit_once('.') else {
4747+ eprintln!("no segments in nsid? nsid={nsid}");
4848+ return nsid;
4949+ };
5050+ pre
5151+}
5252+5353+fn total_users(rollups: &PartitionHandle) -> anyhow::Result<()> {
5454+ eprintln!("scanning all-time rollups...");
5555+ let mut global_sketch = Sketch::<14>::default();
5656+ let mut all_time_count = 0u64;
5757+ let prefix_bytes = AllTimeRollupStaticPrefix::default().to_db_bytes()?;
5858+ for kv in rollups.prefix(prefix_bytes) {
5959+ let (key_bytes, val_bytes) = kv?;
6060+ let _key = db_complete::<AllTimeRollupKey>(&key_bytes)?;
6161+ let val = db_complete::<CountsValue>(&val_bytes)?;
6262+ global_sketch.merge(val.dids());
6363+ all_time_count += 1;
6464+ }
6565+ println!("groups scanned: {all_time_count}");
6666+ println!("estimated distinct users: {}", global_sketch.estimate());
6767+ Ok(())
6868+}
6969+7070+/// Scan weekly rollups once, returning week -> (merged sketch, per-group entries)
7171+/// Only non-excluded groups are included.
7272+#[expect(clippy::type_complexity)]
7373+fn scan_weekly(
7474+ rollups: &PartitionHandle,
7575+) -> anyhow::Result<BTreeMap<u64, (Sketch<14>, Vec<(String, u64)>)>> {
7676+ eprintln!("scanning weekly rollups...");
7777+ let mut weekly_data: BTreeMap<u64, (Sketch<14>, Vec<(String, u64)>)> = BTreeMap::new();
7878+ let prefix_bytes = WeeklyRollupStaticPrefix::default().to_db_bytes()?;
7979+ let mut scanned = 0u64;
8080+ for kv in rollups.prefix(prefix_bytes) {
8181+ let (key_bytes, val_bytes) = kv?;
8282+ let key = db_complete::<WeeklyRollupKey>(&key_bytes)?;
8383+ let val = db_complete::<CountsValue>(&val_bytes)?;
8484+ let week_us = key.cursor().to_raw_u64();
8585+ let nsid_str = key.collection().to_string();
8686+ let estimate = val.dids().estimate() as u64;
8787+8888+ let entry = weekly_data
8989+ .entry(week_us)
9090+ .or_insert_with(|| (Sketch::<14>::default(), Vec::new()));
9191+9292+ if !is_excluded(&nsid_str) {
9393+ entry.0.merge(val.dids());
9494+ entry.1.push((nsid_str, estimate));
9595+ }
9696+9797+ scanned += 1;
9898+ if scanned.is_multiple_of(500_000) {
9999+ eprintln!(" ...scanned {scanned} weekly entries");
100100+ }
101101+ }
102102+ eprintln!(" total weekly entries scanned: {scanned}");
103103+ Ok(weekly_data)
104104+}
105105+106106+fn weekly_users(rollups: &PartitionHandle) -> anyhow::Result<()> {
107107+ let weekly_data = scan_weekly(rollups)?;
108108+ println!("week\test_users");
109109+ for (&week_us, (sketch, _)) in &weekly_data {
110110+ let week = WeekTruncatedCursor::try_from_raw_u64(week_us)?;
111111+ println!("{}\t{}", week_label(week), sketch.estimate());
112112+ }
113113+ Ok(())
114114+}
115115+116116+fn weekly_groups(rollups: &PartitionHandle) -> anyhow::Result<()> {
117117+ let weekly_data = scan_weekly(rollups)?;
118118+ println!("week\tgroups");
119119+ for (&week_us, (_, entries)) in &weekly_data {
120120+ let week = WeekTruncatedCursor::try_from_raw_u64(week_us)?;
121121+ let count = entries.iter().filter(|(_, est)| *est > 10).count();
122122+ println!("{}\t{}", week_label(week), count);
123123+ }
124124+ Ok(())
125125+}
126126+127127+fn weekly_parents(rollups: &PartitionHandle) -> anyhow::Result<()> {
128128+ let weekly_data = scan_weekly(rollups)?;
129129+ println!("week\tparents\ttop parent prefixes");
130130+ for (&week_us, (_, entries)) in &weekly_data {
131131+ let week = WeekTruncatedCursor::try_from_raw_u64(week_us)?;
132132+ let mut parent_counts: BTreeMap<&str, usize> = BTreeMap::new();
133133+ for (nsid, est) in entries {
134134+ if *est > 10 {
135135+ let parent = parent_prefix(nsid);
136136+ *parent_counts.entry(parent).or_default() += 1;
137137+ }
138138+ }
139139+ let total_parents = parent_counts.len();
140140+ let mut sorted: Vec<_> = parent_counts.into_iter().collect();
141141+ sorted.sort_by_key(|c| std::cmp::Reverse(c.1));
142142+ let top: Vec<String> = sorted
143143+ .iter()
144144+ .take(5)
145145+ .map(|(prefix, count)| format!("{prefix}({count})"))
146146+ .collect();
147147+ println!(
148148+ "{}\t{}\t{}",
149149+ week_label(week),
150150+ total_parents,
151151+ top.join(", ")
152152+ );
153153+ }
154154+ Ok(())
155155+}
156156+157157+fn main() -> anyhow::Result<()> {
158158+ let cli = Cli::parse();
159159+160160+ eprintln!("opening db at {:?}...", cli.data);
161161+ let keyspace = Config::new(&cli.data).open()?;
162162+ let rollups = keyspace.open_partition("rollups", PartitionCreateOptions::default())?;
163163+164164+ match cli.command {
165165+ Command::TotalUsers => total_users(&rollups),
166166+ Command::WeeklyUsers => weekly_users(&rollups),
167167+ Command::WeeklyGroups => weekly_groups(&rollups),
168168+ Command::WeeklyParents => weekly_parents(&rollups),
169169+ }
170170+}
+3-3
ufos/src/error.rs
···2828 InitError(String),
2929 #[error("DB seems to be in a bad state: {0}")]
3030 BadStateError(String),
3131- #[error("Fjall error")]
3131+ #[error("Fjall error: {0}")]
3232 FjallError(#[from] fjall::Error),
3333- #[error("LSM-tree error (from fjall)")]
3333+ #[error("LSM-tree error (from fjall): {0}")]
3434 FjallLsmError(#[from] fjall::LsmError),
3535- #[error("Bytes encoding error")]
3535+ #[error("Bytes encoding error: {0}")]
3636 EncodingError(#[from] EncodingError),
3737 #[error("If you ever see this, there's a bug in the code. The error was stolen")]
3838 Stolen,
+27-21
ufos/src/main.rs
···2626struct Args {
2727 /// Jetstream server to connect to (exclusive with --fixture). Provide either a wss:// URL, or a shorhand value:
2828 /// 'us-east-1', 'us-east-2', 'us-west-1', or 'us-west-2'
2929- #[arg(long)]
2929+ #[arg(long, env = "UFOS_JETSTREAM")]
3030 jetstream: String,
3131 /// allow changing jetstream endpoints
3232- #[arg(long, action)]
3232+ #[arg(long, action, env = "UFOS_JETSTREAM_FORCE")]
3333 jetstream_force: bool,
3434 /// don't request zstd-compressed jetstream events
3535 ///
3636 /// reduces CPU at the expense of more ingress bandwidth
3737- #[arg(long, action)]
3737+ #[arg(long, action, env = "UFOS_JETSTREAM_NO_ZSTD")]
3838 jetstream_no_zstd: bool,
3939+ /// ufos server's listen address
4040+ #[arg(long, env = "UFOS_BIND")]
4141+ #[clap(default_value = "0.0.0.0:9990")]
4242+ bind: std::net::SocketAddr,
3943 /// Location to store persist data to disk
4040- #[arg(long)]
4444+ #[arg(long, env = "UFOS_DATA")]
4145 data: PathBuf,
4246 /// DEBUG: don't start the jetstream consumer or its write loop
4343- #[arg(long, action)]
4747+ #[arg(long, action, env = "UFOS_PAUSE_WRITER")]
4448 pause_writer: bool,
4549 /// Adjust runtime settings like background task intervals for efficient backfill
4646- #[arg(long, action)]
5050+ #[arg(long, action, env = "UFOS_BACKFILL_MODE")]
4751 backfill: bool,
4852 /// DEBUG: force the rw loop to fall behind by pausing it
4953 /// todo: restore this
5054 #[arg(long, action)]
5155 pause_rw: bool,
5256 /// reset the rollup cursor, scrape through missed things in the past (backfill)
5353- #[arg(long, action)]
5757+ #[arg(long, action, env = "UFOS_REROLL")]
5458 reroll: bool,
5559 /// DEBUG: interpret jetstream as a file fixture
5656- #[arg(long, action)]
6060+ #[arg(long, action, env = "UFOS_JETSTREAM_FIXTURE")]
5761 jetstream_fixture: bool,
5862 /// HOPEFULLY only needed once
5963 ///
···6165 /// them before at all (oops)
6266 #[arg(long, action)]
6367 fjall_records_gc: bool,
6868+ /// enable metrics collection and serving
6969+ #[arg(long, action, env = "UFOS_COLLECT_METRICS")]
7070+ collect_metrics: bool,
7171+ /// metrics server's listen address
7272+ #[arg(long, env = "UFOS_BIND_METRICS")]
7373+ #[clap(default_value = "0.0.0.0:8765")]
7474+ bind_metrics: std::net::SocketAddr,
6475}
65766677#[tokio::main]
···104115 let mut consumer_tasks: JoinSet<anyhow::Result<()>> = JoinSet::new();
105116106117 println!("starting server with storage...");
107107- let serving = server::serve(read_store.clone());
118118+ let serving = server::serve(read_store.clone(), args.bind);
108119 whatever_tasks.spawn(async move {
109120 serving.await.map_err(|e| {
110121 log::warn!("server ended: {e}");
···157168 Ok(())
158169 });
159170160160- install_metrics_server()?;
171171+ if args.collect_metrics {
172172+ log::trace!("installing metrics server...");
173173+ install_metrics_server(args.bind_metrics)?;
174174+ }
161175162176 for (i, t) in consumer_tasks.join_all().await.iter().enumerate() {
163177 log::warn!("task {i} done: {t:?}");
···171185 Ok(())
172186}
173187174174-fn install_metrics_server() -> anyhow::Result<()> {
188188+fn install_metrics_server(bind: std::net::SocketAddr) -> anyhow::Result<()> {
175189 log::info!("installing metrics server...");
176176- let host = [0, 0, 0, 0];
177177- let port = 8765;
178190 PrometheusBuilder::new()
179191 .set_quantiles(&[0.5, 0.9, 0.99, 1.0])?
180192 .set_bucket_duration(Duration::from_secs(60))?
181193 .set_bucket_count(std::num::NonZero::new(10).unwrap()) // count * duration = 10 mins. stuff doesn't happen that fast here.
182194 .set_enable_unit_suffix(false) // this seemed buggy for constellation (sometimes wouldn't engage)
183183- .with_http_listener((host, port))
195195+ .with_http_listener(bind)
184196 .install()?;
185185- log::info!(
186186- "metrics server installed! listening on http://{}.{}.{}.{}:{port}",
187187- host[0],
188188- host[1],
189189- host[2],
190190- host[3]
191191- );
197197+ log::info!("metrics server installed! listening on {bind}");
192198 Ok(())
193199}
194200
···268268 Some(parent_host),
269269 );
270270 }
271271- if let Some(ref app) = params.app {
272272- if !allowed_hosts.contains(app) {
273273- return err("Login is not allowed for this app", false, Some(app));
274274- }
271271+ if let Some(ref app) = params.app
272272+ && !allowed_hosts.contains(app)
273273+ {
274274+ return err("Login is not allowed for this app", false, Some(app));
275275 }
276276 let parent_origin = url.origin().ascii_serialization();
277277 if parent_origin == "null" {