This commit is contained in:
Aykhan Shahsuvarov 2025-05-19 01:49:56 +04:00
commit e6fec752f9
52 changed files with 4337 additions and 0 deletions

1
.gitignore vendored Normal file
View File

@ -0,0 +1 @@
*.env

33
.golangci.yml Normal file
View File

@ -0,0 +1,33 @@
version: "2"
run:
go: "1.24"
concurrency: 8
timeout: 10m
linters:
default: none
enable:
- asasalint
- asciicheck
- errcheck
- gomodguard
- goprintffuncname
- govet
- ineffassign
- misspell
- nakedret
- nolintlint
- prealloc
- reassign
- staticcheck
- unconvert
- unused
- whitespace
settings:
staticcheck:
checks:
- "all"
- "-S1002"
- "-ST1000"

661
LICENSE Normal file
View File

@ -0,0 +1,661 @@
GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU Affero General Public License is a free, copyleft license for
software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
our General Public Licenses are intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
Developers that use our General Public Licenses protect your rights
with two steps: (1) assert copyright on the software, and (2) offer
you this License which gives you legal permission to copy, distribute
and/or modify the software.
A secondary benefit of defending all users' freedom is that
improvements made in alternate versions of the program, if they
receive widespread use, become available for other developers to
incorporate. Many developers of free software are heartened and
encouraged by the resulting cooperation. However, in the case of
software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its
source code to the public.
The GNU Affero General Public License is designed specifically to
ensure that, in such cases, the modified source code becomes available
to the community. It requires the operator of a network server to
provide the source code of the modified version running there to the
users of that server. Therefore, public use of a modified version, on
a publicly accessible server, gives the public access to the source
code of the modified version.
An older license, called the Affero General Public License and
published by Affero, was designed to accomplish similar goals. This is
a different license, not a version of the Affero GPL, but Affero has
released a new version of the Affero GPL which permits relicensing under
this license.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU Affero General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Remote Network Interaction; Use with the GNU General Public License.
Notwithstanding any other provision of this License, if you modify the
Program, your modified version must prominently offer all users
interacting with it remotely through a computer network (if your version
supports such interaction) an opportunity to receive the Corresponding
Source of your version by providing access to the Corresponding Source
from a network server at no charge, through some standard or customary
means of facilitating copying of software. This Corresponding Source
shall include the Corresponding Source for any work covered by version 3
of the GNU General Public License that is incorporated pursuant to the
following paragraph.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the work with which it is combined will remain governed by version
3 of the GNU General Public License.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU Affero General Public License from time to time. Such new versions
will be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU Affero General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU Affero General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU Affero General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If your software can interact with users remotely through a computer
network, you should also make sure that it provides a way for users to
get its source. For example, if your program is a web application, its
interface could display a "Source" link that leads users to an archive
of the code. There are many ways you could offer source, and different
solutions will be better for different programs; see section 13 for the
specific requirements.
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU AGPL, see
<https://www.gnu.org/licenses/>.

60
Makefile Normal file
View File

@ -0,0 +1,60 @@
# Equivalent Makefile for Taskfile.yaml
.PHONY: ftl fmt tidy lint run-consumer run-feedgen-az run-api run-manager generate-env
# Default value for ARGS if not provided on the command line
ARGS ?=
# Runs fmt, tidy, and lint sequentially
ftl:
$(MAKE) fmt
$(MAKE) tidy
$(MAKE) lint
# Format Go code
fmt:
gofmt -w -d .
# Tidy Go modules
tidy:
go mod tidy
# Run golangci-lint
lint:
golangci-lint run
# Run the consumer application, loading environment from dotenv files
run-consumer:
set -a; \
. config/app/.consumer.env; \
. config/app/.mongodb.env; \
set +a; \
go run cmd/consumer/main.go $(ARGS)
# Run the feedgen-az application, loading environment from dotenv files
run-feedgen-az:
set -a; \
. config/app/feedgen/.az.env; \
. config/app/.mongodb.env; \
set +a; \
go run cmd/feedgen/az/main.go $(ARGS)
# Run the api application, loading environment from dotenv files
run-api:
set -a; \
. config/app/.api.env; \
. config/app/.mongodb.env; \
set +a; \
go run cmd/api/main.go
# Run the manager application with arguments (no dotenv)
run-manager:
go run cmd/manager/main.go $(ARGS)
# Generate env files from templates
generate-env:
cp config/app/consumer.env.example config/app/.consumer.env
cp config/app/api.env.example config/app/.api.env
cp config/app/mongodb.env.example config/app/.mongodb.env
cp config/app/feedgen/az.env.example config/app/feedgen/.az.env
cp config/mongodb/env.example config/mongodb/.env

59
README.md Normal file
View File

@ -0,0 +1,59 @@
# Bluesky Feed Generator
A Go-based feed generator service for Bluesky social platform that includes components for streaming and processing posts, generating feeds, and exposing them via an API.
## Overview
This project is a custom feed generator for Bluesky (ATProto), implementing the "AzPulse" feed. The application consists of several components working together:
- [**API**](./cmd/api): Serves feed data to Bluesky clients
- [**Consumer**](./cmd/consumer): Streams and processes posts from the Bluesky firehose
- [**FeedGen**](./cmd/feedgen): Processes posts and generates the feed content
- [**Manager**](./cmd/manager): CLI tool for managing feed generator records on Bluesky
## Architecture
The system follows a microservices architecture with the following components:
- MongoDB for data storage
- Multiple services communicating through the database
- Each service deployed as a separate container
## Pre-Built docker images
- **API**: `git.aykhans.me/bsky/feedgen-api:latest`
- **Consumer**: `git.aykhans.me/bsky/feedgen-consumer:latest`
- **FeedGen Az**: `git.aykhans.me/bsky/feedgen-generator-az:latest`
- **Manager**: `git.aykhans.me/bsky/feedgen-manager:latest`
## Getting Started
### Prerequisites
- Docker and Docker Compose
- Go 1.24+
### Running with Docker Compose
```bash
docker compose up
```
This will start all necessary services:
- MongoDB database
- Consumer service (streams posts from Bluesky)
- FeedGen service (generates the AZ feed)
- API service (serves feed data to clients)
## Development
For local development without Docker you can checkout the Taskfile and Makefile for development tasks.
## Configuration
All services are configured via environment variables. See the docker-compose.yml file for examples and default values.
## License
This project is licensed under the AGPL-3.0 License, please see the [LICENSE](./LICENSE) file for details.

78
Taskfile.yml Normal file
View File

@ -0,0 +1,78 @@
# https://taskfile.dev
version: "3"
tasks:
ftl:
cmds:
- task: fmt
- task: tidy
- task: lint
fmt: gofmt -w -d .
tidy: go mod tidy
lint: golangci-lint run
run-consumer:
cmd: go run cmd/consumer/main.go {{.CLI_ARGS}}
dotenv:
- config/app/.consumer.env
- config/app/.mongodb.env
run-feedgen-az:
cmd: go run cmd/feedgen/az/main.go {{.CLI_ARGS}}
dotenv:
- config/app/feedgen/.az.env
- config/app/.mongodb.env
run-api:
cmd: go run cmd/api/main.go
dotenv:
- config/app/.api.env
- config/app/.mongodb.env
run-manager:
cmd: go run cmd/manager/main.go {{.CLI_ARGS}}
generate-env:
desc: Generate env files from templates
cmds:
- cp config/app/consumer.env.example config/app/.consumer.env
- cp config/app/api.env.example config/app/.api.env
- cp config/app/mongodb.env.example config/app/.mongodb.env
- cp config/app/feedgen/az.env.example config/app/feedgen/.az.env
- cp config/mongodb/env.example config/mongodb/.env
docker-publish-all:
desc: Publish docker images for all services
cmds:
- task: docker-publish-api
- task: docker-publish-consumer
- task: docker-publish-feedgen-az
- task: docker-publish-manager
docker-publish-api:
desc: Publish docker image for api service
cmds:
- docker build -t git.aykhans.me/bsky/feedgen-api:latest -f ./cmd/api/Dockerfile .
- docker push git.aykhans.me/bsky/feedgen-api:latest
docker-publish-consumer:
desc: Publish docker image for consumer service
cmds:
- docker build -t git.aykhans.me/bsky/feedgen-consumer:latest -f ./cmd/consumer/Dockerfile .
- docker push git.aykhans.me/bsky/feedgen-consumer:latest
docker-publish-feedgen-az:
desc: Publish docker image for feedgen-az service
cmds:
- docker build -t git.aykhans.me/bsky/feedgen-generator-az:latest -f ./cmd/feedgen/az/Dockerfile .
- docker push git.aykhans.me/bsky/feedgen-generator-az:latest
docker-publish-manager:
desc: Publish docker image for manager service
cmds:
- docker build -t git.aykhans.me/bsky/feedgen-manager:latest -f ./cmd/manager/Dockerfile .
- docker push git.aykhans.me/bsky/feedgen-manager:latest

17
cmd/api/Dockerfile Normal file
View File

@ -0,0 +1,17 @@
FROM golang:1.24-alpine AS builder
WORKDIR /src
COPY go.mod go.sum ./
COPY ../../pkg ./pkg
COPY ../../cmd/api ./cmd/api
RUN CGO_ENABLED=0 go build -ldflags "-s -w" -o api ./cmd/api/main.go
FROM gcr.io/distroless/static-debian12:latest
WORKDIR /app
COPY --from=builder /src/api .
ENTRYPOINT ["/app/api"]

30
cmd/api/README.md Normal file
View File

@ -0,0 +1,30 @@
# API Service
## Overview
The API service is responsible for serving custom Bluesky feeds to clients. It implements the necessary endpoints required by the Bluesky protocol to deliver feed content.
**Pre-Built Docker Image**: `git.aykhans.me/bsky/feedgen-api:latest`
## API Endpoints
- `GET /.well-known/did.json`: DID configuration
- `GET /xrpc/app.bsky.feed.describeFeedGenerator`: Describe the feed generator
- `GET /xrpc/app.bsky.feed.getFeedSkeleton`: Main feed endpoint
## Running the Service
### Docker
```bash
docker build -f cmd/api/Dockerfile -t bsky-feedgen-api .
docker run --env-file config/app/.api.env --env-file config/app/.mongodb.env -p 8421:8421 bsky-feedgen-api
```
### Local Development
```bash
task run-api
# or
make run-api
```

60
cmd/api/main.go Normal file
View File

@ -0,0 +1,60 @@
package main
import (
"context"
"os"
"os/signal"
"syscall"
"github.com/aykhans/bsky-feedgen/pkg/api"
"github.com/aykhans/bsky-feedgen/pkg/config"
"github.com/aykhans/bsky-feedgen/pkg/feed"
"github.com/aykhans/bsky-feedgen/pkg/logger"
"github.com/aykhans/bsky-feedgen/pkg/storage/mongodb"
"github.com/aykhans/bsky-feedgen/pkg/storage/mongodb/collections"
)
func main() {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
go listenForTermination(func() { cancel() })
apiConfig, errMap := config.NewAPIConfig()
if errMap != nil {
logger.Log.Error("API ENV error", "error", errMap.ToStringMap())
os.Exit(1)
}
mongoDBConfig, errMap := config.NewMongoDBConfig()
if errMap != nil {
logger.Log.Error("mongodb ENV error", "error", errMap.ToStringMap())
os.Exit(1)
}
client, err := mongodb.NewDB(ctx, mongoDBConfig)
if err != nil {
logger.Log.Error("mongodb connection error", "error", err)
os.Exit(1)
}
feedAzCollection, err := collections.NewFeedAzCollection(client)
if err != nil {
logger.Log.Error(err.Error())
os.Exit(1)
}
feeds := []feed.Feed{
feed.NewFeedAz("AzPulse", apiConfig.FeedgenPublisherDID, feedAzCollection),
}
if err := api.Run(ctx, apiConfig, feeds); err != nil {
logger.Log.Error("API error", "error", err)
}
}
func listenForTermination(do func()) {
sigChan := make(chan os.Signal, 1)
signal.Notify(sigChan, syscall.SIGINT, syscall.SIGTERM)
<-sigChan
do()
}

17
cmd/consumer/Dockerfile Normal file
View File

@ -0,0 +1,17 @@
FROM golang:1.24-alpine AS builder
WORKDIR /src
COPY go.mod go.sum ./
COPY ../../pkg ./pkg
COPY ../../cmd/consumer ./cmd/consumer
RUN CGO_ENABLED=0 go build -ldflags "-s -w" -o consumer ./cmd/consumer/main.go
FROM gcr.io/distroless/static-debian12:latest
WORKDIR /app
COPY --from=builder /src/consumer .
ENTRYPOINT ["/app/consumer"]

40
cmd/consumer/README.md Normal file
View File

@ -0,0 +1,40 @@
# Consumer Service
## Overview
The Consumer service is responsible for connecting to the Bluesky firehose, processing incoming posts, and storing them in MongoDB for later use by the feed generator.
**Pre-Built Docker Image**: `git.aykhans.me/bsky/feedgen-consumer:latest`
## Features
- Connects to the Bluesky firehose websocket
- Processes and filters incoming posts
- Stores relevant post data in MongoDB
- Includes data management via cron jobs
- Implements collection size limits
- Prunes older data to prevent storage issues
## Command Line Options
- `-cursor`: Specify the starting point for data consumption
- `last-consumed`: Resume from the last processed data (default)
- `first-stream`: Start from the beginning of the firehose
- `current-stream`: Start from the current position in the firehose
## Running the Service
### Docker
```bash
docker build -f cmd/consumer/Dockerfile -t bsky-feedgen-consumer .
docker --env-file config/app/.consumer.env --env-file config/app/.mongodb.env run bsky-feedgen-consumer
```
### Local Development
```bash
task run-consumer
# or
make run-consumer
```

122
cmd/consumer/main.go Normal file
View File

@ -0,0 +1,122 @@
package main
import (
"context"
"flag"
"fmt"
"os"
"os/signal"
"strings"
"syscall"
"time"
"github.com/aykhans/bsky-feedgen/pkg/consumer"
"github.com/aykhans/bsky-feedgen/pkg/types"
"github.com/aykhans/bsky-feedgen/pkg/config"
"github.com/aykhans/bsky-feedgen/pkg/logger"
"github.com/aykhans/bsky-feedgen/pkg/storage/mongodb"
"github.com/aykhans/bsky-feedgen/pkg/storage/mongodb/collections"
)
func main() {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
go listenForTermination(func() { cancel() })
flag.Usage = func() {
fmt.Println(
`Usage:
consumer [flags]
Flags:
-h, -help Display this help message
-cursor string Specify the starting point for data consumption (default: last-consumed)
Options:
last-consumed: Resume from the last processed data in storage
first-stream: Start from the beginning of the firehose
current-stream: Start from the current position in the firehose stream`)
}
var cursorOption types.ConsumerCursor
flag.Var(&cursorOption, "cursor", "")
flag.Parse()
if args := flag.Args(); len(args) > 0 {
if len(args) == 1 {
fmt.Printf("unexpected argument: %s\n\n", args[0])
} else {
fmt.Printf("unexpected arguments: %v\n\n", strings.Join(args, ", "))
}
flag.CommandLine.Usage()
os.Exit(1)
}
if cursorOption == "" {
_ = cursorOption.Set("")
}
consumerConfig, errMap := config.NewConsumerConfig()
if errMap != nil {
logger.Log.Error("consumer ENV error", "error", errMap.ToStringMap())
os.Exit(1)
}
mongoDBConfig, errMap := config.NewMongoDBConfig()
if errMap != nil {
logger.Log.Error("mongodb ENV error", "error", errMap.ToStringMap())
os.Exit(1)
}
client, err := mongodb.NewDB(ctx, mongoDBConfig)
if err != nil {
logger.Log.Error("mongodb connection error", "error", err)
os.Exit(1)
}
postCollection, err := collections.NewPostCollection(client)
if err != nil {
logger.Log.Error(err.Error())
os.Exit(1)
}
startCrons(ctx, consumerConfig, postCollection)
logger.Log.Info("Cron jobs started")
err = consumer.ConsumeAndSaveToMongoDB(
ctx,
postCollection,
"wss://bsky.network",
cursorOption,
consumerConfig.PostMaxDate, // Save only posts created before PostMaxDate
10*time.Second, // Save consumed data to MongoDB every 10 seconds
)
if err != nil {
logger.Log.Error(err.Error())
}
}
func startCrons(ctx context.Context, consumerConfig *config.ConsumerConfig, postCollection *collections.PostCollection) {
// Post collection cutoff
go func() {
for {
startTime := time.Now()
deleteCount, err := postCollection.CutoffByCount(ctx, consumerConfig.PostCollectionCutoffCronMaxDocument)
if err != nil {
logger.Log.Error("Post collection cutoff cron error", "error", err)
}
elapsedTime := time.Since(startTime)
logger.Log.Info("Post collection cutoff cron completed", "count", deleteCount, "time", elapsedTime)
time.Sleep(consumerConfig.PostCollectionCutoffCronDelay)
}
}()
}
func listenForTermination(do func()) {
sigChan := make(chan os.Signal, 1)
signal.Notify(sigChan, syscall.SIGINT, syscall.SIGTERM)
<-sigChan
do()
}

17
cmd/feedgen/az/Dockerfile Normal file
View File

@ -0,0 +1,17 @@
FROM golang:1.24-alpine AS builder
WORKDIR /src
COPY go.mod go.sum ./
COPY ../../pkg ./pkg
COPY ../../cmd/feedgen/az ./cmd/feedgen/az
RUN CGO_ENABLED=0 go build -ldflags "-s -w" -o feedgen ./cmd/feedgen/az/main.go
FROM gcr.io/distroless/static-debian12:latest
WORKDIR /app
COPY --from=builder /src/feedgen .
ENTRYPOINT ["/app/feedgen"]

38
cmd/feedgen/az/README.md Normal file
View File

@ -0,0 +1,38 @@
# AzPulse Feed Generator Service
## Overview
The AzPulse Feed Generator service processes posts stored by the Consumer service and generates feed content that will be served by the API service. It implements the logic for the "AzPulse" feed, which showcases selected content from the Bluesky network.
**Pre-Built Docker Image**: `git.aykhans.me/bsky/feedgen-generator-az:latest`
## Features
- Processes posts from MongoDB
- Applies custom feed generation logic for the AzPulse feed
- Stores feed results in MongoDB for API service to access
- Manages feed data lifecycle with automatic pruning
- Runs as a background service with cron jobs
## Command Line Options
- `-cursor`: Specify the starting point for feed data generation
- `last-generated`: Resume from the last generated data (default)
- `first-post`: Start from the beginning of the posts collection
## Running the Service
### Docker
```bash
docker build -f cmd/feedgen/az/Dockerfile -t bsky-feedgen-az .
docker --env-file config/app/feedgen/.az.env --enf-file config/app/.mongodb.env run bsky-feedgen-az
```
### Local Development
```bash
task run-feedgen-az
# or
make run-feedgen-az
```

140
cmd/feedgen/az/main.go Normal file
View File

@ -0,0 +1,140 @@
package main
import (
"context"
"flag"
"fmt"
"os"
"os/signal"
"strings"
"syscall"
"time"
"github.com/aykhans/bsky-feedgen/pkg/generator"
"github.com/aykhans/bsky-feedgen/pkg/types"
"github.com/aykhans/bsky-feedgen/pkg/config"
"github.com/aykhans/bsky-feedgen/pkg/logger"
"github.com/aykhans/bsky-feedgen/pkg/storage/mongodb"
"github.com/aykhans/bsky-feedgen/pkg/storage/mongodb/collections"
)
func main() {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
go listenForTermination(func() { cancel() })
flag.Usage = func() {
fmt.Println(
`Usage:
feedgen-az [flags]
Flags:
-h, -help Display this help message
-cursor string Specify the starting point for feed data generation (default: last-generated)
Options:
last-generated: Resume from the last generated data in storage
first-post: Start from the beginning of the posts`)
}
var cursorOption types.GeneratorCursor
flag.Var(&cursorOption, "cursor", "")
flag.Parse()
if args := flag.Args(); len(args) > 0 {
if len(args) == 1 {
fmt.Printf("unexpected argument: %s\n\n", args[0])
} else {
fmt.Printf("unexpected arguments: %v\n\n", strings.Join(args, ", "))
}
flag.CommandLine.Usage()
os.Exit(1)
}
if cursorOption == "" {
_ = cursorOption.Set("")
}
feedGenAzConfig, errMap := config.NewFeedGenAzConfig()
if errMap != nil {
logger.Log.Error("feedGenAzConfig ENV error", "error", errMap.ToStringMap())
os.Exit(1)
}
mongoDBConfig, errMap := config.NewMongoDBConfig()
if errMap != nil {
logger.Log.Error("mongodb ENV error", "error", errMap.ToStringMap())
os.Exit(1)
}
client, err := mongodb.NewDB(ctx, mongoDBConfig)
if err != nil {
logger.Log.Error("mongodb connection error", "error", err)
os.Exit(1)
}
postCollection, err := collections.NewPostCollection(client)
if err != nil {
logger.Log.Error(err.Error())
os.Exit(1)
}
feedAzCollection, err := collections.NewFeedAzCollection(client)
if err != nil {
logger.Log.Error(err.Error())
os.Exit(1)
}
feedGeneratorAz := generator.NewFeedGeneratorAz(postCollection, feedAzCollection)
startCrons(ctx, feedGenAzConfig, feedGeneratorAz, feedAzCollection, cursorOption)
logger.Log.Info("Cron jobs started")
<-ctx.Done()
}
func startCrons(
ctx context.Context,
feedGenAzConfig *config.FeedGenAzConfig,
feedGeneratorAz *generator.FeedGeneratorAz,
feedAzCollection *collections.FeedAzCollection,
cursorOption types.GeneratorCursor,
) {
// Feed az generator
go func() {
for {
startTime := time.Now()
err := feedGeneratorAz.Start(ctx, cursorOption, 1)
if err != nil {
logger.Log.Error("Feed az generator cron error", "error", err)
}
elapsedTime := time.Since(startTime)
logger.Log.Info("Feed az generator cron completed", "time", elapsedTime)
time.Sleep(feedGenAzConfig.GeneratorCronDelay)
}
}()
// feed_az collection cutoff
go func() {
for {
startTime := time.Now()
deleteCount, err := feedAzCollection.CutoffByCount(ctx, feedGenAzConfig.CollectionMaxDocument)
if err != nil {
logger.Log.Error("feed_az collection cutoff cron error", "error", err)
}
elapsedTime := time.Since(startTime)
logger.Log.Info("feed_az collection cutoff cron completed", "count", deleteCount, "time", elapsedTime)
time.Sleep(feedGenAzConfig.CutoffCronDelay)
}
}()
}
func listenForTermination(do func()) {
sigChan := make(chan os.Signal, 1)
signal.Notify(sigChan, syscall.SIGINT, syscall.SIGTERM)
<-sigChan
do()
}

18
cmd/manager/Dockerfile Normal file
View File

@ -0,0 +1,18 @@
FROM golang:1.24-alpine AS builder
WORKDIR /src
COPY go.mod go.sum ./
COPY ../../pkg ./pkg
COPY ../../cmd/manager ./cmd/manager
RUN CGO_ENABLED=0 go build -ldflags "-s -w" -o manager ./cmd/manager/main.go
FROM gcr.io/distroless/static-debian12:latest
WORKDIR /app
COPY --from=builder /src/manager .
ENTRYPOINT ["/app/manager"]
CMD ["help"]

47
cmd/manager/README.md Normal file
View File

@ -0,0 +1,47 @@
# Feed Manager CLI Tool
## Overview
The Feed Manager is a command-line interface (CLI) tool that allows users to create, update, and delete feed generator records on the Bluesky network.
**Pre-Built Docker Image**: `git.aykhans.me/bsky/feedgen-manager:latest`
## Commands
### Create a Feed Generator
```bash
task run-manager create
# or
make run-manager create
```
This will prompt for:
- Your Bluesky handle
- Your Bluesky password
- Feed generator hostname
- Record short name (for the URL)
- Display name
- Description (optional)
- Avatar image path (optional)
### Update a Feed Generator
```bash
task run-manager update
# or
make run-manager update
```
Allows updating the properties of an existing feed generator record.
### Delete a Feed Generator
```bash
task run-manager delete
# or
make run-manager delete
```
Permenantly removes a feed generator record from the Bluesky network.

268
cmd/manager/main.go Normal file
View File

@ -0,0 +1,268 @@
package main
import (
"bufio"
"context"
"fmt"
"os"
"os/signal"
"strings"
"syscall"
"github.com/aykhans/bsky-feedgen/pkg/manage"
"github.com/spf13/cobra"
"golang.org/x/term"
)
func main() {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
go listenForTermination(func() {
cancel()
fmt.Println()
os.Exit(130)
})
var rootCmd = &cobra.Command{
Use: "feedgen-manager",
Short: "BlueSkye Feed Generator client CLI",
Long: "A command-line tool for managing feed generators on Bluesky",
CompletionOptions: cobra.CompletionOptions{HiddenDefaultCmd: true},
}
var createCmd = &cobra.Command{
Use: "create",
Short: "Create a feed generator record",
Run: func(cmd *cobra.Command, args []string) {
handle := prompt("Enter your Bluesky handle", "")
if handle == "" {
fmt.Println("\nError: handle is required")
os.Exit(1)
}
password := promptPassword("Enter your Bluesky password (preferably an App Password)")
if handle == "" {
fmt.Println("\nError: password is required")
os.Exit(1)
}
service := prompt("Optionally, enter a custom PDS service to sign in with", manage.DefaultPDSHost)
feedgenHostname := prompt("Enter the feed generator hostname (e.g. 'feeds.bsky.example.com')", "")
if feedgenHostname == "" {
fmt.Println("\nError: hostname is required")
os.Exit(1)
}
recordKey := prompt("Enter a short name for the record. This will be shown in the feed's URL and should be unique.", "")
if recordKey == "" {
fmt.Println("\nError: short name is required")
os.Exit(1)
}
displayName := prompt("Enter a display name for your feed", "")
if displayName == "" {
fmt.Println("\nError: display name is required")
os.Exit(1)
}
description := prompt("Optionally, enter a brief description of your feed", "")
avatar := prompt("Optionally, enter a local path to an avatar that will be used for the feed", "")
client, err := manage.NewClientWithAuth(ctx, manage.NewClient(&service), handle, password)
if err != nil {
fmt.Printf("\nAuthentication failed: %v", err)
os.Exit(1)
}
err = manage.CreateFeedGenerator(
ctx,
client,
displayName,
toPtr(description),
toPtr(avatar),
"did:web:"+feedgenHostname,
recordKey,
)
if err != nil {
fmt.Printf("\nFailed to create feed generator record: %v\n", err)
os.Exit(1)
}
fmt.Println("\nFeed generator created successfully! 🎉")
},
}
var updateCmd = &cobra.Command{
Use: "update",
Short: "Update a feed generator record",
Run: func(cmd *cobra.Command, args []string) {
handle := prompt("Enter your Bluesky handle", "")
if handle == "" {
fmt.Println("\nError: handle is required")
os.Exit(1)
}
password := promptPassword("Enter your Bluesky password (preferably an App Password)")
if handle == "" {
fmt.Println("\nError: password is required")
os.Exit(1)
}
service := prompt("Optionally, enter a custom PDS service to sign in with", manage.DefaultPDSHost)
feedgenHostname := prompt("Optionally, enter the feed generator hostname (e.g. 'feeds.bsky.example.com')", "")
recordKey := prompt("Enter short name of the record", "")
if recordKey == "" {
fmt.Println("\nError: short name is required")
os.Exit(1)
}
displayName := prompt("Optionally, enter a display name for your feed", "")
description := prompt("Optionally, enter a brief description of your feed", "")
avatar := prompt("Optionally, enter a local path to an avatar that will be used for the feed", "")
client, err := manage.NewClientWithAuth(ctx, manage.NewClient(&service), handle, password)
if err != nil {
fmt.Printf("\nAuthentication failed: %v", err)
os.Exit(1)
}
var did *string
if feedgenHostname != "" {
did = toPtr("did:web:" + feedgenHostname)
}
err = manage.UpdateFeedGenerator(
ctx,
client,
toPtr(displayName),
toPtr(description),
toPtr(avatar),
did,
recordKey,
)
if err != nil {
fmt.Printf("\nFailed to update feed generator record: %v\n", err)
os.Exit(1)
}
fmt.Println("\nFeed generator updated successfully! 🎉")
},
}
var deleteCmd = &cobra.Command{
Use: "delete",
Short: "Delete a feed generator record",
Run: func(cmd *cobra.Command, args []string) {
handle := prompt("Enter your Bluesky handle", "")
if handle == "" {
fmt.Println("\nError: handle is required")
os.Exit(1)
}
password := promptPassword("Enter your Bluesky password (preferably an App Password)")
if handle == "" {
fmt.Println("\nError: password is required")
os.Exit(1)
}
service := prompt("Optionally, enter a custom PDS service to sign in with", manage.DefaultPDSHost)
recordKey := prompt("Enter short name of the record", "")
if recordKey == "" {
fmt.Println("\nError: short name is required")
os.Exit(1)
}
confirm := promptConfirm("Are you sure you want to delete this record? Any likes that your feed has will be lost", false)
if !confirm {
fmt.Println("\nAborting...")
return
}
client, err := manage.NewClientWithAuth(ctx, manage.NewClient(&service), handle, password)
if err != nil {
fmt.Printf("\nAuthentication failed: %v", err)
os.Exit(1)
}
err = manage.DeleteFeedGenerator(ctx, client, recordKey)
if err != nil {
fmt.Printf("\nFailed to delete feed generator record: %v\n", err)
os.Exit(1)
}
fmt.Println("\nFeed generator deleted successfully! 🎉")
},
}
rootCmd.AddCommand(createCmd)
rootCmd.AddCommand(updateCmd)
rootCmd.AddCommand(deleteCmd)
if err := rootCmd.Execute(); err != nil {
fmt.Println(err)
os.Exit(1)
}
}
// <-------------- Utils -------------->
func listenForTermination(do func()) {
sigChan := make(chan os.Signal, 1)
signal.Notify(sigChan, syscall.SIGINT, syscall.SIGTERM)
<-sigChan
do()
}
func toPtr[T comparable](value T) *T {
var zero T
if value == zero {
return nil
}
return &value
}
func prompt(label string, defaultValue string) string {
if defaultValue != "" {
fmt.Printf("%s [%s]: ", label, defaultValue)
} else {
fmt.Printf("%s: ", label)
}
reader := bufio.NewReader(os.Stdin)
input, _ := reader.ReadString('\n')
input = strings.TrimSpace(input)
if input == "" {
return defaultValue
}
return input
}
func promptPassword(label string) string {
fmt.Printf("%s: ", label)
password, _ := term.ReadPassword(int(os.Stdin.Fd()))
fmt.Println()
return string(password)
}
func promptConfirm(label string, defaultValue bool) bool {
defaultStr := "y/N"
if defaultValue {
defaultStr = "Y/n"
}
fmt.Printf("%s [%s]: ", label, defaultStr)
reader := bufio.NewReader(os.Stdin)
input, _ := reader.ReadString('\n')
input = strings.ToLower(strings.TrimSpace(input))
if input == "" {
return defaultValue
}
return input == "y" || input == "yes"
}

View File

@ -0,0 +1,3 @@
FEEDGEN_HOSTNAME=https://feeds.bsky.example.com # Not required for the development environment
FEEDGEN_PUBLISHER_DID=did:plc:qwertyuiopp # Not required for the development environment
API_PORT=8421

View File

@ -0,0 +1,3 @@
POST_MAX_DATE=720h # Save only posts created in the last month
POST_COLLECTION_CUTOFF_CRON_DELAY=30m # 30 minutes
POST_COLLECTION_CUTOFF_CRON_MAX_DOCUMENT=10000000 # Delete post documents after 10 million

View File

@ -0,0 +1,3 @@
FEED_AZ_GENERATER_CRON_DELAY=1m # 1 minute
FEED_AZ_COLLECTION_CUTOFF_CRON_DELAY=30m # 30 minutes
FEED_AZ_COLLECTION_CUTOFF_CRON_MAX_DOCUMENT=500000 # Delete post documents after 500 thousand

View File

@ -0,0 +1,4 @@
MONGODB_HOST=localhost
MONGODB_PORT=27017
MONGODB_USERNAME=
MONGODB_PASSWORD=

View File

@ -0,0 +1,2 @@
MONGO_INITDB_ROOT_USERNAME=
MONGO_INITDB_ROOT_PASSWORD=

53
docker-compose.yml Normal file
View File

@ -0,0 +1,53 @@
# This configuration is for development purposes only, not for production use.
x-common-mongodb-environment: &common-mongodb-environment
MONGODB_HOST: mongodb
MONGODB_PORT: 27017
services:
mongodb:
image: mongo
ports:
- 27017:27017
healthcheck:
test: echo 'db.runCommand("ping").ok' | mongosh --quiet
interval: 10s
timeout: 5s
retries: 5
start_period: 20s
consumer:
build:
dockerfile: ./cmd/consumer/Dockerfile
environment:
<<: *common-mongodb-environment
POST_MAX_DATE: 720h # Save only posts created in the last month
POST_COLLECTION_CUTOFF_CRON_DELAY: 30m # 30 minutes
POST_COLLECTION_CUTOFF_CRON_MAX_DOCUMENT: 10000000 # Delete post documents after 10 million
depends_on:
mongodb:
condition: service_healthy
feedgen_az:
build:
dockerfile: ./cmd/feedgen/az/Dockerfile
environment:
<<: *common-mongodb-environment
FEED_AZ_GENERATER_CRON_DELAY: 1m # 1 minute
FEED_AZ_COLLECTION_CUTOFF_CRON_DELAY: 30m # 30 minutes
FEED_AZ_COLLECTION_CUTOFF_CRON_MAX_DOCUMENT: 500000 # Delete post documents after 500 thousand
depends_on:
mongodb:
condition: service_healthy
api:
build:
dockerfile: ./cmd/api/Dockerfile
ports:
- 8421:8421
environment:
<<: *common-mongodb-environment
API_PORT: 8421
depends_on:
mongodb:
condition: service_healthy

116
go.mod Normal file
View File

@ -0,0 +1,116 @@
module github.com/aykhans/bsky-feedgen
go 1.24
require (
github.com/bluesky-social/indigo v0.0.0-20250516010818-f8de501bd6a0
github.com/gorilla/websocket v1.5.1
go.mongodb.org/mongo-driver v1.17.3
)
require (
github.com/RussellLuo/slidingwindow v0.0.0-20200528002341-535bb99d338b // indirect
github.com/beorn7/perks v1.0.1 // indirect
github.com/carlmjohnson/versioninfo v0.22.5 // indirect
github.com/cespare/xxhash/v2 v2.2.0 // indirect
github.com/decred/dcrd/dcrec/secp256k1/v4 v4.2.0 // indirect
github.com/felixge/httpsnoop v1.0.4 // indirect
github.com/go-logr/logr v1.4.1 // indirect
github.com/go-logr/stdr v1.2.2 // indirect
github.com/goccy/go-json v0.10.2 // indirect
github.com/gocql/gocql v1.7.0 // indirect
github.com/gogo/protobuf v1.3.2 // indirect
github.com/golang/snappy v0.0.4 // indirect
github.com/google/uuid v1.4.0 // indirect
github.com/hailocab/go-hostpool v0.0.0-20160125115350-e80d13ce29ed // indirect
github.com/hashicorp/go-cleanhttp v0.5.2 // indirect
github.com/hashicorp/go-retryablehttp v0.7.5 // indirect
github.com/hashicorp/golang-lru v1.0.2 // indirect
github.com/hashicorp/golang-lru/v2 v2.0.7 // indirect
github.com/inconshreveable/mousetrap v1.1.0 // indirect
github.com/ipfs/bbloom v0.0.4 // indirect
github.com/ipfs/go-block-format v0.2.0 // indirect
github.com/ipfs/go-blockservice v0.5.2 // indirect
github.com/ipfs/go-cid v0.4.1 // indirect
github.com/ipfs/go-datastore v0.6.0 // indirect
github.com/ipfs/go-ipfs-blockstore v1.3.1 // indirect
github.com/ipfs/go-ipfs-ds-help v1.1.1 // indirect
github.com/ipfs/go-ipfs-exchange-interface v0.2.1 // indirect
github.com/ipfs/go-ipfs-util v0.0.3 // indirect
github.com/ipfs/go-ipld-cbor v0.1.0 // indirect
github.com/ipfs/go-ipld-format v0.6.0 // indirect
github.com/ipfs/go-ipld-legacy v0.2.1 // indirect
github.com/ipfs/go-libipfs v0.7.0 // indirect
github.com/ipfs/go-log v1.0.5 // indirect
github.com/ipfs/go-log/v2 v2.5.1 // indirect
github.com/ipfs/go-merkledag v0.11.0 // indirect
github.com/ipfs/go-metrics-interface v0.0.1 // indirect
github.com/ipfs/go-verifcid v0.0.3 // indirect
github.com/ipld/go-car v0.6.1-0.20230509095817-92d28eb23ba4 // indirect
github.com/ipld/go-codec-dagpb v1.6.0 // indirect
github.com/ipld/go-ipld-prime v0.21.0 // indirect
github.com/jackc/pgpassfile v1.0.0 // indirect
github.com/jackc/pgservicefile v0.0.0-20221227161230-091c0ba34f0a // indirect
github.com/jackc/pgx/v5 v5.5.0 // indirect
github.com/jackc/puddle/v2 v2.2.1 // indirect
github.com/jbenet/goprocess v0.1.4 // indirect
github.com/jinzhu/inflection v1.0.0 // indirect
github.com/jinzhu/now v1.1.5 // indirect
github.com/klauspost/compress v1.17.3 // indirect
github.com/klauspost/cpuid/v2 v2.2.7 // indirect
github.com/lestrrat-go/blackmagic v1.0.1 // indirect
github.com/lestrrat-go/httpcc v1.0.1 // indirect
github.com/lestrrat-go/httprc v1.0.4 // indirect
github.com/lestrrat-go/iter v1.0.2 // indirect
github.com/lestrrat-go/jwx/v2 v2.0.12 // indirect
github.com/lestrrat-go/option v1.0.1 // indirect
github.com/mattn/go-isatty v0.0.20 // indirect
github.com/mattn/go-sqlite3 v1.14.22 // indirect
github.com/matttproud/golang_protobuf_extensions/v2 v2.0.0 // indirect
github.com/minio/sha256-simd v1.0.1 // indirect
github.com/montanaflynn/stats v0.7.1 // indirect
github.com/mr-tron/base58 v1.2.0 // indirect
github.com/multiformats/go-base32 v0.1.0 // indirect
github.com/multiformats/go-base36 v0.2.0 // indirect
github.com/multiformats/go-multibase v0.2.0 // indirect
github.com/multiformats/go-multihash v0.2.3 // indirect
github.com/multiformats/go-varint v0.0.7 // indirect
github.com/opentracing/opentracing-go v1.2.0 // indirect
github.com/polydawn/refmt v0.89.1-0.20221221234430-40501e09de1f // indirect
github.com/prometheus/client_golang v1.17.0 // indirect
github.com/prometheus/client_model v0.5.0 // indirect
github.com/prometheus/common v0.45.0 // indirect
github.com/prometheus/procfs v0.12.0 // indirect
github.com/segmentio/asm v1.2.0 // indirect
github.com/spaolacci/murmur3 v1.1.0 // indirect
github.com/spf13/cobra v1.9.1
github.com/spf13/pflag v1.0.6 // indirect
github.com/whyrusleeping/cbor-gen v0.2.1-0.20241030202151-b7a6831be65e // indirect
github.com/whyrusleeping/go-did v0.0.0-20240828165449-bcaa7ae21371
github.com/xdg-go/pbkdf2 v1.0.0 // indirect
github.com/xdg-go/scram v1.1.2 // indirect
github.com/xdg-go/stringprep v1.0.4 // indirect
github.com/youmark/pkcs8 v0.0.0-20240726163527-a2c0da244d78 // indirect
gitlab.com/yawning/secp256k1-voi v0.0.0-20230925100816-f2616030848b // indirect
gitlab.com/yawning/tuplehash v0.0.0-20230713102510-df83abbf9a02 // indirect
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.46.1 // indirect
go.opentelemetry.io/otel v1.21.0 // indirect
go.opentelemetry.io/otel/metric v1.21.0 // indirect
go.opentelemetry.io/otel/trace v1.21.0 // indirect
go.uber.org/atomic v1.11.0 // indirect
go.uber.org/multierr v1.11.0 // indirect
go.uber.org/zap v1.26.0 // indirect
golang.org/x/crypto v0.38.0 // indirect
golang.org/x/net v0.23.0 // indirect
golang.org/x/sync v0.14.0 // indirect
golang.org/x/sys v0.33.0 // indirect
golang.org/x/term v0.32.0
golang.org/x/text v0.25.0 // indirect
golang.org/x/time v0.3.0 // indirect
golang.org/x/xerrors v0.0.0-20231012003039-104605ab7028 // indirect
google.golang.org/protobuf v1.33.0 // indirect
gopkg.in/inf.v0 v0.9.1 // indirect
gorm.io/driver/postgres v1.5.7 // indirect
gorm.io/gorm v1.25.9 // indirect
lukechampine.com/blake3 v1.2.1 // indirect
)

464
go.sum Normal file
View File

@ -0,0 +1,464 @@
github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU=
github.com/RussellLuo/slidingwindow v0.0.0-20200528002341-535bb99d338b h1:5/++qT1/z812ZqBvqQt6ToRswSuPZ/B33m6xVHRzADU=
github.com/RussellLuo/slidingwindow v0.0.0-20200528002341-535bb99d338b/go.mod h1:4+EPqMRApwwE/6yo6CxiHoSnBzjRr3jsqer7frxP8y4=
github.com/alexbrainman/goissue34681 v0.0.0-20191006012335-3fc7a47baff5 h1:iW0a5ljuFxkLGPNem5Ui+KBjFJzKg4Fv2fnxe4dvzpM=
github.com/alexbrainman/goissue34681 v0.0.0-20191006012335-3fc7a47baff5/go.mod h1:Y2QMoi1vgtOIfc+6DhrMOGkLoGzqSV2rKp4Sm+opsyA=
github.com/benbjohnson/clock v1.1.0/go.mod h1:J11/hYXuz8f4ySSvYwY0FKfm+ezbsZBKZxNJlLklBHA=
github.com/benbjohnson/clock v1.3.0 h1:ip6w0uFQkncKQ979AypyG0ER7mqUSBdKLOgAle/AT8A=
github.com/benbjohnson/clock v1.3.0/go.mod h1:J11/hYXuz8f4ySSvYwY0FKfm+ezbsZBKZxNJlLklBHA=
github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM=
github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw=
github.com/bitly/go-hostpool v0.0.0-20171023180738-a3a6125de932 h1:mXoPYz/Ul5HYEDvkta6I8/rnYM5gSdSV2tJ6XbZuEtY=
github.com/bitly/go-hostpool v0.0.0-20171023180738-a3a6125de932/go.mod h1:NOuUCSz6Q9T7+igc/hlvDOUdtWKryOrtFyIVABv/p7k=
github.com/bluesky-social/indigo v0.0.0-20250516010818-f8de501bd6a0 h1:dvlM3xGxp4gHAUuJwrL2Y6cW12UBJiRrE9b11meTqwg=
github.com/bluesky-social/indigo v0.0.0-20250516010818-f8de501bd6a0/go.mod h1:ovyxp8AMO1Hoe838vMJUbqHTZaAR8ABM3g3TXu+A5Ng=
github.com/bmizerany/assert v0.0.0-20160611221934-b7ed37b82869 h1:DDGfHa7BWjL4YnC6+E63dPcxHo2sUxDIu8g3QgEJdRY=
github.com/bmizerany/assert v0.0.0-20160611221934-b7ed37b82869/go.mod h1:Ekp36dRnpXw/yCqJaO+ZrUyxD+3VXMFFr56k5XYrpB4=
github.com/carlmjohnson/versioninfo v0.22.5 h1:O00sjOLUAFxYQjlN/bzYTuZiS0y6fWDQjMRvwtKgwwc=
github.com/carlmjohnson/versioninfo v0.22.5/go.mod h1:QT9mph3wcVfISUKd0i9sZfVrPviHuSF+cUtLjm2WSf8=
github.com/cespare/xxhash/v2 v2.2.0 h1:DC2CZ1Ep5Y4k3ZQ899DldepgrayRUGE6BBZ/cd9Cj44=
github.com/cespare/xxhash/v2 v2.2.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
github.com/cpuguy83/go-md2man/v2 v2.0.0-20190314233015-f79a8a8ca69d/go.mod h1:maD7wRr/U5Z6m/iR4s+kqSMx2CaBsrgA7czyZG/E6dU=
github.com/cpuguy83/go-md2man/v2 v2.0.6/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6NIQQ7OS05n1F4g=
github.com/cskr/pubsub v1.0.2 h1:vlOzMhl6PFn60gRlTQQsIfVwaPB/B/8MziK8FhEPt/0=
github.com/cskr/pubsub v1.0.2/go.mod h1:/8MzYXk/NJAz782G8RPkFzXTZVu63VotefPnR9TIRis=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/decred/dcrd/crypto/blake256 v1.0.1/go.mod h1:2OfgNZ5wDpcsFmHmCK5gZTPcCXqlm2ArzUIkw9czNJo=
github.com/decred/dcrd/dcrec/secp256k1/v4 v4.2.0 h1:8UrgZ3GkP4i/CLijOJx79Yu+etlyjdBU4sfcs2WYQMs=
github.com/decred/dcrd/dcrec/secp256k1/v4 v4.2.0/go.mod h1:v57UDF4pDQJcEfFUCRop3lJL149eHGSe9Jvczhzjo/0=
github.com/felixge/httpsnoop v1.0.4 h1:NFTV2Zj1bL4mc9sqWACXbQFVBBg2W3GPvqp8/ESS2Wg=
github.com/felixge/httpsnoop v1.0.4/go.mod h1:m8KPJKqk1gH5J9DgRY2ASl2lWCfGKXixSwevea8zH2U=
github.com/frankban/quicktest v1.14.6 h1:7Xjx+VpznH+oBnejlPUj8oUpdxnVs4f8XU8WnHkI4W8=
github.com/frankban/quicktest v1.14.6/go.mod h1:4ptaffx2x8+WTWXmUCuVU6aPUX1/Mz7zb5vbUoiM6w0=
github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A=
github.com/go-logr/logr v1.4.1 h1:pKouT5E8xu9zeFC39JXRDukb6JFQPXM5p5I91188VAQ=
github.com/go-logr/logr v1.4.1/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=
github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=
github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=
github.com/go-redis/redis v6.15.9+incompatible h1:K0pv1D7EQUjfyoMql+r/jZqCLizCGKFlFgcHWWmHQjg=
github.com/go-redis/redis v6.15.9+incompatible/go.mod h1:NAIEuMOZ/fxfXJIrKDQDz8wamY7mA7PouImQ2Jvg6kA=
github.com/go-yaml/yaml v2.1.0+incompatible/go.mod h1:w2MrLa16VYP0jy6N7M5kHaCkaLENm+P+Tv+MfurjSw0=
github.com/goccy/go-json v0.10.2 h1:CrxCmQqYDkv1z7lO7Wbh2HN93uovUHgrECaO5ZrCXAU=
github.com/goccy/go-json v0.10.2/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I=
github.com/gocql/gocql v1.7.0 h1:O+7U7/1gSN7QTEAaMEsJc1Oq2QHXvCWoF3DFK9HDHus=
github.com/gocql/gocql v1.7.0/go.mod h1:vnlvXyFZeLBF0Wy+RS8hrOdbn0UWsWtdg07XJnFxZ+4=
github.com/gogo/protobuf v1.3.2 h1:Ov1cvc58UF3b5XjBnZv7+opcTcQFZebYjWzi34vdm4Q=
github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69NZV8Q=
github.com/golang/snappy v0.0.3/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q=
github.com/golang/snappy v0.0.4 h1:yAGX7huGHXlcLOEtBnF4w7FQwA26wojNCwOYAEhLjQM=
github.com/golang/snappy v0.0.4/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q=
github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI=
github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
github.com/google/gopacket v1.1.19 h1:ves8RnFZPGiFnTS0uPQStjwru6uO6h+nlr9j6fL7kF8=
github.com/google/gopacket v1.1.19/go.mod h1:iJ8V8n6KS+z2U1A8pUwu8bW5SyEMkXJB8Yo/Vo+TKTo=
github.com/google/renameio v0.1.0/go.mod h1:KWCgfxg9yswjAJkECMjeO8J8rahYeXnNhOm40UhjYkI=
github.com/google/uuid v1.4.0 h1:MtMxsa51/r9yyhkyLsVeVt0B+BGQZzpQiTQ4eHZ8bc4=
github.com/google/uuid v1.4.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1 h1:EGx4pi6eqNxGaHF6qqu48+N2wcFQ5qg5FXgOdqsJ5d8=
github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1/go.mod h1:wJfORRmW1u3UXTncJ5qlYoELFm8eSnnEO6hX4iZ3EWY=
github.com/gorilla/websocket v1.5.1 h1:gmztn0JnHVt9JZquRuzLw3g4wouNVzKL15iLr/zn/QY=
github.com/gorilla/websocket v1.5.1/go.mod h1:x3kM2JMyaluk02fnUJpQuwD2dCS5NDG2ZHL0uE0tcaY=
github.com/hailocab/go-hostpool v0.0.0-20160125115350-e80d13ce29ed h1:5upAirOpQc1Q53c0bnx2ufif5kANL7bfZWcc6VJWJd8=
github.com/hailocab/go-hostpool v0.0.0-20160125115350-e80d13ce29ed/go.mod h1:tMWxXQ9wFIaZeTI9F+hmhFiGpFmhOHzyShyFUhRm0H4=
github.com/hashicorp/go-cleanhttp v0.5.2 h1:035FKYIWjmULyFRBKPs8TBQoi0x6d9G4xc9neXJWAZQ=
github.com/hashicorp/go-cleanhttp v0.5.2/go.mod h1:kO/YDlP8L1346E6Sodw+PrpBSV4/SoxCXGY6BqNFT48=
github.com/hashicorp/go-hclog v0.9.2 h1:CG6TE5H9/JXsFWJCfoIVpKFIkFe6ysEuHirp4DxCsHI=
github.com/hashicorp/go-hclog v0.9.2/go.mod h1:5CU+agLiy3J7N7QjHK5d05KxGsuXiQLrjA0H7acj2lQ=
github.com/hashicorp/go-retryablehttp v0.7.5 h1:bJj+Pj19UZMIweq/iie+1u5YCdGrnxCT9yvm0e+Nd5M=
github.com/hashicorp/go-retryablehttp v0.7.5/go.mod h1:Jy/gPYAdjqffZ/yFGCFV2doI5wjtH1ewM9u8iYVjtX8=
github.com/hashicorp/golang-lru v1.0.2 h1:dV3g9Z/unq5DpblPpw+Oqcv4dU/1omnb4Ok8iPY6p1c=
github.com/hashicorp/golang-lru v1.0.2/go.mod h1:iADmTwqILo4mZ8BN3D2Q6+9jd8WM5uGBxy+E8yxSoD4=
github.com/hashicorp/golang-lru/v2 v2.0.7 h1:a+bsQ5rvGLjzHuww6tVxozPZFVghXaHOwFs4luLUK2k=
github.com/hashicorp/golang-lru/v2 v2.0.7/go.mod h1:QeFd9opnmA6QUJc5vARoKUSoFhyfM2/ZepoAG6RGpeM=
github.com/huin/goupnp v1.0.3 h1:N8No57ls+MnjlB+JPiCVSOyy/ot7MJTqlo7rn+NYSqQ=
github.com/huin/goupnp v1.0.3/go.mod h1:ZxNlw5WqJj6wSsRK5+YfflQGXYfccj5VgQsMNixHM7Y=
github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8=
github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw=
github.com/ipfs/bbloom v0.0.4 h1:Gi+8EGJ2y5qiD5FbsbpX/TMNcJw8gSqr7eyjHa4Fhvs=
github.com/ipfs/bbloom v0.0.4/go.mod h1:cS9YprKXpoZ9lT0n/Mw/a6/aFV6DTjTLYHeA+gyqMG0=
github.com/ipfs/go-bitswap v0.11.0 h1:j1WVvhDX1yhG32NTC9xfxnqycqYIlhzEzLXG/cU1HyQ=
github.com/ipfs/go-bitswap v0.11.0/go.mod h1:05aE8H3XOU+LXpTedeAS0OZpcO1WFsj5niYQH9a1Tmk=
github.com/ipfs/go-block-format v0.2.0 h1:ZqrkxBA2ICbDRbK8KJs/u0O3dlp6gmAuuXUJNiW1Ycs=
github.com/ipfs/go-block-format v0.2.0/go.mod h1:+jpL11nFx5A/SPpsoBn6Bzkra/zaArfSmsknbPMYgzM=
github.com/ipfs/go-blockservice v0.5.2 h1:in9Bc+QcXwd1apOVM7Un9t8tixPKdaHQFdLSUM1Xgk8=
github.com/ipfs/go-blockservice v0.5.2/go.mod h1:VpMblFEqG67A/H2sHKAemeH9vlURVavlysbdUI632yk=
github.com/ipfs/go-bs-sqlite3 v0.0.0-20221122195556-bfcee1be620d h1:9V+GGXCuOfDiFpdAHz58q9mKLg447xp0cQKvqQrAwYE=
github.com/ipfs/go-bs-sqlite3 v0.0.0-20221122195556-bfcee1be620d/go.mod h1:pMbnFyNAGjryYCLCe59YDLRv/ujdN+zGJBT1umlvYRM=
github.com/ipfs/go-cid v0.4.1 h1:A/T3qGvxi4kpKWWcPC/PgbvDA2bjVLO7n4UeVwnbs/s=
github.com/ipfs/go-cid v0.4.1/go.mod h1:uQHwDeX4c6CtyrFwdqyhpNcxVewur1M7l7fNU7LKwZk=
github.com/ipfs/go-datastore v0.6.0 h1:JKyz+Gvz1QEZw0LsX1IBn+JFCJQH4SJVFtM4uWU0Myk=
github.com/ipfs/go-datastore v0.6.0/go.mod h1:rt5M3nNbSO/8q1t4LNkLyUwRs8HupMeN/8O4Vn9YAT8=
github.com/ipfs/go-detect-race v0.0.1 h1:qX/xay2W3E4Q1U7d9lNs1sU9nvguX0a7319XbyQ6cOk=
github.com/ipfs/go-detect-race v0.0.1/go.mod h1:8BNT7shDZPo99Q74BpGMK+4D8Mn4j46UU0LZ723meps=
github.com/ipfs/go-ds-flatfs v0.5.1 h1:ZCIO/kQOS/PSh3vcF1H6a8fkRGS7pOfwfPdx4n/KJH4=
github.com/ipfs/go-ds-flatfs v0.5.1/go.mod h1:RWTV7oZD/yZYBKdbVIFXTX2fdY2Tbvl94NsWqmoyAX4=
github.com/ipfs/go-ipfs-blockstore v1.3.1 h1:cEI9ci7V0sRNivqaOr0elDsamxXFxJMMMy7PTTDQNsQ=
github.com/ipfs/go-ipfs-blockstore v1.3.1/go.mod h1:KgtZyc9fq+P2xJUiCAzbRdhhqJHvsw8u2Dlqy2MyRTE=
github.com/ipfs/go-ipfs-blocksutil v0.0.1 h1:Eh/H4pc1hsvhzsQoMEP3Bke/aW5P5rVM1IWFJMcGIPQ=
github.com/ipfs/go-ipfs-blocksutil v0.0.1/go.mod h1:Yq4M86uIOmxmGPUHv/uI7uKqZNtLb449gwKqXjIsnRk=
github.com/ipfs/go-ipfs-delay v0.0.1 h1:r/UXYyRcddO6thwOnhiznIAiSvxMECGgtv35Xs1IeRQ=
github.com/ipfs/go-ipfs-delay v0.0.1/go.mod h1:8SP1YXK1M1kXuc4KJZINY3TQQ03J2rwBG9QfXmbRPrw=
github.com/ipfs/go-ipfs-ds-help v1.1.1 h1:B5UJOH52IbcfS56+Ul+sv8jnIV10lbjLF5eOO0C66Nw=
github.com/ipfs/go-ipfs-ds-help v1.1.1/go.mod h1:75vrVCkSdSFidJscs8n4W+77AtTpCIAdDGAwjitJMIo=
github.com/ipfs/go-ipfs-exchange-interface v0.2.1 h1:jMzo2VhLKSHbVe+mHNzYgs95n0+t0Q69GQ5WhRDZV/s=
github.com/ipfs/go-ipfs-exchange-interface v0.2.1/go.mod h1:MUsYn6rKbG6CTtsDp+lKJPmVt3ZrCViNyH3rfPGsZ2E=
github.com/ipfs/go-ipfs-exchange-offline v0.3.0 h1:c/Dg8GDPzixGd0MC8Jh6mjOwU57uYokgWRFidfvEkuA=
github.com/ipfs/go-ipfs-exchange-offline v0.3.0/go.mod h1:MOdJ9DChbb5u37M1IcbrRB02e++Z7521fMxqCNRrz9s=
github.com/ipfs/go-ipfs-pq v0.0.3 h1:YpoHVJB+jzK15mr/xsWC574tyDLkezVrDNeaalQBsTE=
github.com/ipfs/go-ipfs-pq v0.0.3/go.mod h1:btNw5hsHBpRcSSgZtiNm/SLj5gYIZ18AKtv3kERkRb4=
github.com/ipfs/go-ipfs-routing v0.3.0 h1:9W/W3N+g+y4ZDeffSgqhgo7BsBSJwPMcyssET9OWevc=
github.com/ipfs/go-ipfs-routing v0.3.0/go.mod h1:dKqtTFIql7e1zYsEuWLyuOU+E0WJWW8JjbTPLParDWo=
github.com/ipfs/go-ipfs-util v0.0.3 h1:2RFdGez6bu2ZlZdI+rWfIdbQb1KudQp3VGwPtdNCmE0=
github.com/ipfs/go-ipfs-util v0.0.3/go.mod h1:LHzG1a0Ig4G+iZ26UUOMjHd+lfM84LZCrn17xAKWBvs=
github.com/ipfs/go-ipld-cbor v0.1.0 h1:dx0nS0kILVivGhfWuB6dUpMa/LAwElHPw1yOGYopoYs=
github.com/ipfs/go-ipld-cbor v0.1.0/go.mod h1:U2aYlmVrJr2wsUBU67K4KgepApSZddGRDWBYR0H4sCk=
github.com/ipfs/go-ipld-format v0.6.0 h1:VEJlA2kQ3LqFSIm5Vu6eIlSxD/Ze90xtc4Meten1F5U=
github.com/ipfs/go-ipld-format v0.6.0/go.mod h1:g4QVMTn3marU3qXchwjpKPKgJv+zF+OlaKMyhJ4LHPg=
github.com/ipfs/go-ipld-legacy v0.2.1 h1:mDFtrBpmU7b//LzLSypVrXsD8QxkEWxu5qVxN99/+tk=
github.com/ipfs/go-ipld-legacy v0.2.1/go.mod h1:782MOUghNzMO2DER0FlBR94mllfdCJCkTtDtPM51otM=
github.com/ipfs/go-libipfs v0.7.0 h1:Mi54WJTODaOL2/ZSm5loi3SwI3jI2OuFWUrQIkJ5cpM=
github.com/ipfs/go-libipfs v0.7.0/go.mod h1:KsIf/03CqhICzyRGyGo68tooiBE2iFbI/rXW7FhAYr0=
github.com/ipfs/go-log v1.0.5 h1:2dOuUCB1Z7uoczMWgAyDck5JLb72zHzrMnGnCNNbvY8=
github.com/ipfs/go-log v1.0.5/go.mod h1:j0b8ZoR+7+R99LD9jZ6+AJsrzkPbSXbZfGakb5JPtIo=
github.com/ipfs/go-log/v2 v2.1.3/go.mod h1:/8d0SH3Su5Ooc31QlL1WysJhvyOTDCjcCZ9Axpmri6g=
github.com/ipfs/go-log/v2 v2.5.1 h1:1XdUzF7048prq4aBjDQQ4SL5RxftpRGdXhNRwKSAlcY=
github.com/ipfs/go-log/v2 v2.5.1/go.mod h1:prSpmC1Gpllc9UYWxDiZDreBYw7zp4Iqp1kOLU9U5UI=
github.com/ipfs/go-merkledag v0.11.0 h1:DgzwK5hprESOzS4O1t/wi6JDpyVQdvm9Bs59N/jqfBY=
github.com/ipfs/go-merkledag v0.11.0/go.mod h1:Q4f/1ezvBiJV0YCIXvt51W/9/kqJGH4I1LsA7+djsM4=
github.com/ipfs/go-metrics-interface v0.0.1 h1:j+cpbjYvu4R8zbleSs36gvB7jR+wsL2fGD6n0jO4kdg=
github.com/ipfs/go-metrics-interface v0.0.1/go.mod h1:6s6euYU4zowdslK0GKHmqaIZ3j/b/tL7HTWtJ4VPgWY=
github.com/ipfs/go-peertaskqueue v0.8.1 h1:YhxAs1+wxb5jk7RvS0LHdyiILpNmRIRnZVztekOF0pg=
github.com/ipfs/go-peertaskqueue v0.8.1/go.mod h1:Oxxd3eaK279FxeydSPPVGHzbwVeHjatZ2GA8XD+KbPU=
github.com/ipfs/go-verifcid v0.0.3 h1:gmRKccqhWDocCRkC+a59g5QW7uJw5bpX9HWBevXa0zs=
github.com/ipfs/go-verifcid v0.0.3/go.mod h1:gcCtGniVzelKrbk9ooUSX/pM3xlH73fZZJDzQJRvOUw=
github.com/ipld/go-car v0.6.1-0.20230509095817-92d28eb23ba4 h1:oFo19cBmcP0Cmg3XXbrr0V/c+xU9U1huEZp8+OgBzdI=
github.com/ipld/go-car v0.6.1-0.20230509095817-92d28eb23ba4/go.mod h1:6nkFF8OmR5wLKBzRKi7/YFJpyYR7+oEn1DX+mMWnlLA=
github.com/ipld/go-car/v2 v2.13.1 h1:KnlrKvEPEzr5IZHKTXLAEub+tPrzeAFQVRlSQvuxBO4=
github.com/ipld/go-car/v2 v2.13.1/go.mod h1:QkdjjFNGit2GIkpQ953KBwowuoukoM75nP/JI1iDJdo=
github.com/ipld/go-codec-dagpb v1.6.0 h1:9nYazfyu9B1p3NAgfVdpRco3Fs2nFC72DqVsMj6rOcc=
github.com/ipld/go-codec-dagpb v1.6.0/go.mod h1:ANzFhfP2uMJxRBr8CE+WQWs5UsNa0pYtmKZ+agnUw9s=
github.com/ipld/go-ipld-prime v0.21.0 h1:n4JmcpOlPDIxBcY037SVfpd1G+Sj1nKZah0m6QH9C2E=
github.com/ipld/go-ipld-prime v0.21.0/go.mod h1:3RLqy//ERg/y5oShXXdx5YIp50cFGOanyMctpPjsvxQ=
github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM=
github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg=
github.com/jackc/pgservicefile v0.0.0-20221227161230-091c0ba34f0a h1:bbPeKD0xmW/Y25WS6cokEszi5g+S0QxI/d45PkRi7Nk=
github.com/jackc/pgservicefile v0.0.0-20221227161230-091c0ba34f0a/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM=
github.com/jackc/pgx/v5 v5.5.0 h1:NxstgwndsTRy7eq9/kqYc/BZh5w2hHJV86wjvO+1xPw=
github.com/jackc/pgx/v5 v5.5.0/go.mod h1:Ig06C2Vu0t5qXC60W8sqIthScaEnFvojjj9dSljmHRA=
github.com/jackc/puddle/v2 v2.2.1 h1:RhxXJtFG022u4ibrCSMSiu5aOq1i77R3OHKNJj77OAk=
github.com/jackc/puddle/v2 v2.2.1/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4=
github.com/jackpal/go-nat-pmp v1.0.2 h1:KzKSgb7qkJvOUTqYl9/Hg/me3pWgBmERKrTGD7BdWus=
github.com/jackpal/go-nat-pmp v1.0.2/go.mod h1:QPH045xvCAeXUZOxsnwmrtiCoxIr9eob+4orBN1SBKc=
github.com/jbenet/go-cienv v0.1.0/go.mod h1:TqNnHUmJgXau0nCzC7kXWeotg3J9W34CUv5Djy1+FlA=
github.com/jbenet/goprocess v0.1.4 h1:DRGOFReOMqqDNXwW70QkacFW0YN9QnwLV0Vqk+3oU0o=
github.com/jbenet/goprocess v0.1.4/go.mod h1:5yspPrukOVuOLORacaBi858NqyClJPQxYZlqdZVfqY4=
github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E=
github.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc=
github.com/jinzhu/now v1.1.5 h1:/o9tlHleP7gOFmsnYNz3RGnqzefHA47wQpKrrdTIwXQ=
github.com/jinzhu/now v1.1.5/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8=
github.com/jtolds/gls v4.20.0+incompatible h1:xdiiI2gbIgH/gLH7ADydsJ1uDOEzR8yvV7C0MuV77Wo=
github.com/jtolds/gls v4.20.0+incompatible/go.mod h1:QJZ7F/aHp+rZTRtaJ1ow/lLfFfVYBRgL+9YlvaHOwJU=
github.com/kisielk/errcheck v1.5.0/go.mod h1:pFxgyoBC7bSaBwPgfKdkLd5X25qrDl4LWUI2bnpBCr8=
github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck=
github.com/klauspost/compress v1.17.3 h1:qkRjuerhUU1EmXLYGkSH6EZL+vPSxIrYjLNAK4slzwA=
github.com/klauspost/compress v1.17.3/go.mod h1:/dCuZOvVtNoHsyb+cuJD3itjs3NbnF6KH9zAO4BDxPM=
github.com/klauspost/cpuid/v2 v2.2.7 h1:ZWSB3igEs+d0qvnxR/ZBzXVmxkgt8DdzP6m9pfuVLDM=
github.com/klauspost/cpuid/v2 v2.2.7/go.mod h1:Lcz8mBdAVJIBVzewtcLocK12l3Y+JytZYpaMropDUws=
github.com/koron/go-ssdp v0.0.3 h1:JivLMY45N76b4p/vsWGOKewBQu6uf39y8l+AQ7sDKx8=
github.com/koron/go-ssdp v0.0.3/go.mod h1:b2MxI6yh02pKrsyNoQUsk4+YNikaGhe4894J+Q5lDvA=
github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=
github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
github.com/lestrrat-go/blackmagic v1.0.1 h1:lS5Zts+5HIC/8og6cGHb0uCcNCa3OUt1ygh3Qz2Fe80=
github.com/lestrrat-go/blackmagic v1.0.1/go.mod h1:UrEqBzIR2U6CnzVyUtfM6oZNMt/7O7Vohk2J0OGSAtU=
github.com/lestrrat-go/httpcc v1.0.1 h1:ydWCStUeJLkpYyjLDHihupbn2tYmZ7m22BGkcvZZrIE=
github.com/lestrrat-go/httpcc v1.0.1/go.mod h1:qiltp3Mt56+55GPVCbTdM9MlqhvzyuL6W/NMDA8vA5E=
github.com/lestrrat-go/httprc v1.0.4 h1:bAZymwoZQb+Oq8MEbyipag7iSq6YIga8Wj6GOiJGdI8=
github.com/lestrrat-go/httprc v1.0.4/go.mod h1:mwwz3JMTPBjHUkkDv/IGJ39aALInZLrhBp0X7KGUZlo=
github.com/lestrrat-go/iter v1.0.2 h1:gMXo1q4c2pHmC3dn8LzRhJfP1ceCbgSiT9lUydIzltI=
github.com/lestrrat-go/iter v1.0.2/go.mod h1:Momfcq3AnRlRjI5b5O8/G5/BvpzrhoFTZcn06fEOPt4=
github.com/lestrrat-go/jwx/v2 v2.0.12 h1:3d589+5w/b9b7S3DneICPW16AqTyYXB7VRjgluSDWeA=
github.com/lestrrat-go/jwx/v2 v2.0.12/go.mod h1:Mq4KN1mM7bp+5z/W5HS8aCNs5RKZ911G/0y2qUjAQuQ=
github.com/lestrrat-go/option v1.0.0/go.mod h1:5ZHFbivi4xwXxhxY9XHDe2FHo6/Z7WWmtT7T5nBBp3I=
github.com/lestrrat-go/option v1.0.1 h1:oAzP2fvZGQKWkvHa1/SAcFolBEca1oN+mQ7eooNBEYU=
github.com/lestrrat-go/option v1.0.1/go.mod h1:5ZHFbivi4xwXxhxY9XHDe2FHo6/Z7WWmtT7T5nBBp3I=
github.com/libp2p/go-buffer-pool v0.1.0 h1:oK4mSFcQz7cTQIfqbe4MIj9gLW+mnanjyFtc6cdF0Y8=
github.com/libp2p/go-buffer-pool v0.1.0/go.mod h1:N+vh8gMqimBzdKkSMVuydVDq+UV5QTWy5HSiZacSbPg=
github.com/libp2p/go-cidranger v1.1.0 h1:ewPN8EZ0dd1LSnrtuwd4709PXVcITVeuwbag38yPW7c=
github.com/libp2p/go-cidranger v1.1.0/go.mod h1:KWZTfSr+r9qEo9OkI9/SIEeAtw+NNoU0dXIXt15Okic=
github.com/libp2p/go-libp2p v0.25.1 h1:YK+YDCHpYyTvitKWVxa5PfElgIpOONU01X5UcLEwJGA=
github.com/libp2p/go-libp2p v0.25.1/go.mod h1:xnK9/1d9+jeQCVvi/f1g12KqtVi/jP/SijtKV1hML3g=
github.com/libp2p/go-libp2p-asn-util v0.2.0 h1:rg3+Os8jbnO5DxkC7K/Utdi+DkY3q/d1/1q+8WeNAsw=
github.com/libp2p/go-libp2p-asn-util v0.2.0/go.mod h1:WoaWxbHKBymSN41hWSq/lGKJEca7TNm58+gGJi2WsLI=
github.com/libp2p/go-libp2p-record v0.2.0 h1:oiNUOCWno2BFuxt3my4i1frNrt7PerzB3queqa1NkQ0=
github.com/libp2p/go-libp2p-record v0.2.0/go.mod h1:I+3zMkvvg5m2OcSdoL0KPljyJyvNDFGKX7QdlpYUcwk=
github.com/libp2p/go-libp2p-testing v0.12.0 h1:EPvBb4kKMWO29qP4mZGyhVzUyR25dvfUIK5WDu6iPUA=
github.com/libp2p/go-libp2p-testing v0.12.0/go.mod h1:KcGDRXyN7sQCllucn1cOOS+Dmm7ujhfEyXQL5lvkcPg=
github.com/libp2p/go-msgio v0.3.0 h1:mf3Z8B1xcFN314sWX+2vOTShIE0Mmn2TXn3YCUQGNj0=
github.com/libp2p/go-msgio v0.3.0/go.mod h1:nyRM819GmVaF9LX3l03RMh10QdOroF++NBbxAb0mmDM=
github.com/libp2p/go-nat v0.1.0 h1:MfVsH6DLcpa04Xr+p8hmVRG4juse0s3J8HyNWYHffXg=
github.com/libp2p/go-nat v0.1.0/go.mod h1:X7teVkwRHNInVNWQiO/tAiAVRwSr5zoRz4YSTC3uRBM=
github.com/libp2p/go-netroute v0.2.1 h1:V8kVrpD8GK0Riv15/7VN6RbUQ3URNZVosw7H2v9tksU=
github.com/libp2p/go-netroute v0.2.1/go.mod h1:hraioZr0fhBjG0ZRXJJ6Zj2IVEVNx6tDTFQfSmcq7mQ=
github.com/mattn/go-isatty v0.0.14/go.mod h1:7GGIvUiUoEMVVmxf/4nioHXj79iQHKdU27kJ6hsGG94=
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
github.com/mattn/go-sqlite3 v1.14.22 h1:2gZY6PC6kBnID23Tichd1K+Z0oS6nE/XwU+Vz/5o4kU=
github.com/mattn/go-sqlite3 v1.14.22/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y=
github.com/matttproud/golang_protobuf_extensions/v2 v2.0.0 h1:jWpvCLoY8Z/e3VKvlsiIGKtc+UG6U5vzxaoagmhXfyg=
github.com/matttproud/golang_protobuf_extensions/v2 v2.0.0/go.mod h1:QUyp042oQthUoa9bqDv0ER0wrtXnBruoNd7aNjkbP+k=
github.com/miekg/dns v1.1.50 h1:DQUfb9uc6smULcREF09Uc+/Gd46YWqJd5DbpPE9xkcA=
github.com/miekg/dns v1.1.50/go.mod h1:e3IlAVfNqAllflbibAZEWOXOQ+Ynzk/dDozDxY7XnME=
github.com/minio/sha256-simd v1.0.1 h1:6kaan5IFmwTNynnKKpDHe6FWHohJOHhCPchzK49dzMM=
github.com/minio/sha256-simd v1.0.1/go.mod h1:Pz6AKMiUdngCLpeTL/RJY1M9rUuPMYujV5xJjtbRSN8=
github.com/montanaflynn/stats v0.7.1 h1:etflOAAHORrCC44V+aR6Ftzort912ZU+YLiSTuV8eaE=
github.com/montanaflynn/stats v0.7.1/go.mod h1:etXPPgVO6n31NxCd9KQUMvCM+ve0ruNzt6R8Bnaayow=
github.com/mr-tron/base58 v1.2.0 h1:T/HDJBh4ZCPbU39/+c3rRvE0uKBQlU27+QI8LJ4t64o=
github.com/mr-tron/base58 v1.2.0/go.mod h1:BinMc/sQntlIE1frQmRFPUoPA1Zkr8VRgBdjWI2mNwc=
github.com/multiformats/go-base32 v0.1.0 h1:pVx9xoSPqEIQG8o+UbAe7DNi51oej1NtK+aGkbLYxPE=
github.com/multiformats/go-base32 v0.1.0/go.mod h1:Kj3tFY6zNr+ABYMqeUNeGvkIC/UYgtWibDcT0rExnbI=
github.com/multiformats/go-base36 v0.2.0 h1:lFsAbNOGeKtuKozrtBsAkSVhv1p9D0/qedU9rQyccr0=
github.com/multiformats/go-base36 v0.2.0/go.mod h1:qvnKE++v+2MWCfePClUEjE78Z7P2a1UV0xHgWc0hkp4=
github.com/multiformats/go-multiaddr v0.8.0 h1:aqjksEcqK+iD/Foe1RRFsGZh8+XFiGo7FgUCZlpv3LU=
github.com/multiformats/go-multiaddr v0.8.0/go.mod h1:Fs50eBDWvZu+l3/9S6xAE7ZYj6yhxlvaVZjakWN7xRs=
github.com/multiformats/go-multiaddr-dns v0.3.1 h1:QgQgR+LQVt3NPTjbrLLpsaT2ufAA2y0Mkk+QRVJbW3A=
github.com/multiformats/go-multiaddr-dns v0.3.1/go.mod h1:G/245BRQ6FJGmryJCrOuTdB37AMA5AMOVuO6NY3JwTk=
github.com/multiformats/go-multiaddr-fmt v0.1.0 h1:WLEFClPycPkp4fnIzoFoV9FVd49/eQsuaL3/CWe167E=
github.com/multiformats/go-multiaddr-fmt v0.1.0/go.mod h1:hGtDIW4PU4BqJ50gW2quDuPVjyWNZxToGUh/HwTZYJo=
github.com/multiformats/go-multibase v0.2.0 h1:isdYCVLvksgWlMW9OZRYJEa9pZETFivncJHmHnnd87g=
github.com/multiformats/go-multibase v0.2.0/go.mod h1:bFBZX4lKCA/2lyOFSAoKH5SS6oPyjtnzK/XTFDPkNuk=
github.com/multiformats/go-multicodec v0.9.0 h1:pb/dlPnzee/Sxv/j4PmkDRxCOi3hXTz3IbPKOXWJkmg=
github.com/multiformats/go-multicodec v0.9.0/go.mod h1:L3QTQvMIaVBkXOXXtVmYE+LI16i14xuaojr/H7Ai54k=
github.com/multiformats/go-multihash v0.2.3 h1:7Lyc8XfX/IY2jWb/gI7JP+o7JEq9hOa7BFvVU9RSh+U=
github.com/multiformats/go-multihash v0.2.3/go.mod h1:dXgKXCXjBzdscBLk9JkjINiEsCKRVch90MdaGiKsvSM=
github.com/multiformats/go-multistream v0.4.1 h1:rFy0Iiyn3YT0asivDUIR05leAdwZq3de4741sbiSdfo=
github.com/multiformats/go-multistream v0.4.1/go.mod h1:Mz5eykRVAjJWckE2U78c6xqdtyNUEhKSM0Lwar2p77Q=
github.com/multiformats/go-varint v0.0.7 h1:sWSGR+f/eu5ABZA2ZpYKBILXTTs9JWpdEM/nEGOHFS8=
github.com/multiformats/go-varint v0.0.7/go.mod h1:r8PUYw/fD/SjBCiKOoDlGF6QawOELpZAu9eioSos/OU=
github.com/opentracing/opentracing-go v1.2.0 h1:uEJPy/1a5RIPAJ0Ov+OIO8OxWu77jEv+1B0VhjKrZUs=
github.com/opentracing/opentracing-go v1.2.0/go.mod h1:GxEUsuufX4nBwe+T+Wl9TAgYrxe9dPLANfrWvHYVTgc=
github.com/petar/GoLLRB v0.0.0-20210522233825-ae3b015fd3e9 h1:1/WtZae0yGtPq+TI6+Tv1WTxkukpXeMlviSxvL7SRgk=
github.com/petar/GoLLRB v0.0.0-20210522233825-ae3b015fd3e9/go.mod h1:x3N5drFsm2uilKKuuYo6LdyD8vZAW55sH/9w+pbo1sw=
github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/polydawn/refmt v0.89.1-0.20221221234430-40501e09de1f h1:VXTQfuJj9vKR4TCkEuWIckKvdHFeJH/huIFJ9/cXOB0=
github.com/polydawn/refmt v0.89.1-0.20221221234430-40501e09de1f/go.mod h1:/zvteZs/GwLtCgZ4BL6CBsk9IKIlexP43ObX9AxTqTw=
github.com/prometheus/client_golang v1.17.0 h1:rl2sfwZMtSthVU752MqfjQozy7blglC+1SOtjMAMh+Q=
github.com/prometheus/client_golang v1.17.0/go.mod h1:VeL+gMmOAxkS2IqfCq0ZmHSL+LjWfWDUmp1mBz9JgUY=
github.com/prometheus/client_model v0.5.0 h1:VQw1hfvPvk3Uv6Qf29VrPF32JB6rtbgI6cYPYQjL0Qw=
github.com/prometheus/client_model v0.5.0/go.mod h1:dTiFglRmd66nLR9Pv9f0mZi7B7fk5Pm3gvsjB5tr+kI=
github.com/prometheus/common v0.45.0 h1:2BGz0eBc2hdMDLnO/8n0jeB3oPrt2D08CekT0lneoxM=
github.com/prometheus/common v0.45.0/go.mod h1:YJmSTw9BoKxJplESWWxlbyttQR4uaEcGyv9MZjVOJsY=
github.com/prometheus/procfs v0.12.0 h1:jluTpSng7V9hY0O2R9DzzJHYb2xULk9VTR1V1R/k6Bo=
github.com/prometheus/procfs v0.12.0/go.mod h1:pcuDEFsWDnvcgNzo4EEweacyhjeA9Zk3cnaOZAZEfOo=
github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4=
github.com/rogpeppe/go-internal v1.10.0 h1:TMyTOH3F/DB16zRVcYyreMH6GnZZrwQVAoYjRBZyWFQ=
github.com/rogpeppe/go-internal v1.10.0/go.mod h1:UQnix2H7Ngw/k4C5ijL5+65zddjncjaFoBhdsK/akog=
github.com/russross/blackfriday/v2 v2.0.1/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
github.com/segmentio/asm v1.2.0 h1:9BQrFxC+YOHJlTlHGkTrFWf59nbL3XnCoFLTwDCI7ys=
github.com/segmentio/asm v1.2.0/go.mod h1:BqMnlJP91P8d+4ibuonYZw9mfnzI9HfxselHZr5aAcs=
github.com/shurcooL/sanitized_anchor_name v1.0.0/go.mod h1:1NzhyTcUVG4SuEtjjoZeVRXNmyL/1OwPU0+IJeTBvfc=
github.com/smartystreets/assertions v1.2.0 h1:42S6lae5dvLc7BrLu/0ugRtcFVjoJNMC/N3yZFZkDFs=
github.com/smartystreets/assertions v1.2.0/go.mod h1:tcbTF8ujkAEcZ8TElKY+i30BzYlVhC/LOxJk7iOWnoo=
github.com/smartystreets/goconvey v1.7.2 h1:9RBaZCeXEQ3UselpuwUQHltGVXvdwm6cv1hgR6gDIPg=
github.com/smartystreets/goconvey v1.7.2/go.mod h1:Vw0tHAZW6lzCRk3xgdin6fKYcG+G3Pg9vgXWeJpQFMM=
github.com/spaolacci/murmur3 v1.1.0 h1:7c1g84S4BPRrfL5Xrdp6fOJ206sU9y293DDHaoy0bLI=
github.com/spaolacci/murmur3 v1.1.0/go.mod h1:JwIasOWyU6f++ZhiEuf87xNszmSA2myDM2Kzu9HwQUA=
github.com/spf13/cobra v1.9.1 h1:CXSaggrXdbHK9CF+8ywj8Amf7PBRmPCOJugH954Nnlo=
github.com/spf13/cobra v1.9.1/go.mod h1:nDyEzZ8ogv936Cinf6g1RU9MRY64Ir93oCnqb9wxYW0=
github.com/spf13/pflag v1.0.6 h1:jFzHGLGAlb3ruxLB8MhbI6A8+AQX/2eW4qeyNZXNp2o=
github.com/spf13/pflag v1.0.6/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4=
github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg=
github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
github.com/urfave/cli v1.22.10/go.mod h1:Gos4lmkARVdJ6EkW0WaNv/tZAAMe9V7XWyB60NtXRu0=
github.com/warpfork/go-testmark v0.12.1 h1:rMgCpJfwy1sJ50x0M0NgyphxYYPMOODIJHhsXyEHU0s=
github.com/warpfork/go-testmark v0.12.1/go.mod h1:kHwy7wfvGSPh1rQJYKayD4AbtNaeyZdcGi9tNJTaa5Y=
github.com/warpfork/go-wish v0.0.0-20220906213052-39a1cc7a02d0 h1:GDDkbFiaK8jsSDJfjId/PEGEShv6ugrt4kYsC5UIDaQ=
github.com/warpfork/go-wish v0.0.0-20220906213052-39a1cc7a02d0/go.mod h1:x6AKhvSSexNrVSrViXSHUEbICjmGXhtgABaHIySUSGw=
github.com/whyrusleeping/cbor v0.0.0-20171005072247-63513f603b11 h1:5HZfQkwe0mIfyDmc1Em5GqlNRzcdtlv4HTNmdpt7XH0=
github.com/whyrusleeping/cbor v0.0.0-20171005072247-63513f603b11/go.mod h1:Wlo/SzPmxVp6vXpGt/zaXhHH0fn4IxgqZc82aKg6bpQ=
github.com/whyrusleeping/cbor-gen v0.2.1-0.20241030202151-b7a6831be65e h1:28X54ciEwwUxyHn9yrZfl5ojgF4CBNLWX7LR0rvBkf4=
github.com/whyrusleeping/cbor-gen v0.2.1-0.20241030202151-b7a6831be65e/go.mod h1:pM99HXyEbSQHcosHc0iW7YFmwnscr+t9Te4ibko05so=
github.com/whyrusleeping/go-did v0.0.0-20240828165449-bcaa7ae21371 h1:W4jEGWdes35iuiiAYNZFOjx+dwzQOBh33kVpc0C0YiE=
github.com/whyrusleeping/go-did v0.0.0-20240828165449-bcaa7ae21371/go.mod h1:39U9RRVr4CKbXpXYopWn+FSH5s+vWu6+RmguSPWAq5s=
github.com/xdg-go/pbkdf2 v1.0.0 h1:Su7DPu48wXMwC3bs7MCNG+z4FhcyEuz5dlvchbq0B0c=
github.com/xdg-go/pbkdf2 v1.0.0/go.mod h1:jrpuAogTd400dnrH08LKmI/xc1MbPOebTwRqcT5RDeI=
github.com/xdg-go/scram v1.1.2 h1:FHX5I5B4i4hKRVRBCFRxq1iQRej7WO3hhBuJf+UUySY=
github.com/xdg-go/scram v1.1.2/go.mod h1:RT/sEzTbU5y00aCK8UOx6R7YryM0iF1N2MOmC3kKLN4=
github.com/xdg-go/stringprep v1.0.4 h1:XLI/Ng3O1Atzq0oBs3TWm+5ZVgkq2aqdlvP9JtoZ6c8=
github.com/xdg-go/stringprep v1.0.4/go.mod h1:mPGuuIYwz7CmR2bT9j4GbQqutWS1zV24gijq1dTyGkM=
github.com/youmark/pkcs8 v0.0.0-20240726163527-a2c0da244d78 h1:ilQV1hzziu+LLM3zUTJ0trRztfwgjqKnBWNtSRkbmwM=
github.com/youmark/pkcs8 v0.0.0-20240726163527-a2c0da244d78/go.mod h1:aL8wCCfTfSfmXjznFBSZNN13rSJjlIOI1fUNAtF7rmI=
github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
github.com/yuin/goldmark v1.3.5/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k=
github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=
gitlab.com/yawning/secp256k1-voi v0.0.0-20230925100816-f2616030848b h1:CzigHMRySiX3drau9C6Q5CAbNIApmLdat5jPMqChvDA=
gitlab.com/yawning/secp256k1-voi v0.0.0-20230925100816-f2616030848b/go.mod h1:/y/V339mxv2sZmYYR64O07VuCpdNZqCTwO8ZcouTMI8=
gitlab.com/yawning/tuplehash v0.0.0-20230713102510-df83abbf9a02 h1:qwDnMxjkyLmAFgcfgTnfJrmYKWhHnci3GjDqcZp1M3Q=
gitlab.com/yawning/tuplehash v0.0.0-20230713102510-df83abbf9a02/go.mod h1:JTnUj0mpYiAsuZLmKjTx/ex3AtMowcCgnE7YNyCEP0I=
go.mongodb.org/mongo-driver v1.17.3 h1:TQyXhnsWfWtgAhMtOgtYHMTkZIfBTpMTsMnd9ZBeHxQ=
go.mongodb.org/mongo-driver v1.17.3/go.mod h1:Hy04i7O2kC4RS06ZrhPRqj/u4DTYkFDAAccj+rVKqgQ=
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.46.1 h1:aFJWCqJMNjENlcleuuOkGAPH82y0yULBScfXcIEdS24=
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.46.1/go.mod h1:sEGXWArGqc3tVa+ekntsN65DmVbVeW+7lTKTjZF3/Fo=
go.opentelemetry.io/otel v1.21.0 h1:hzLeKBZEL7Okw2mGzZ0cc4k/A7Fta0uoPgaJCr8fsFc=
go.opentelemetry.io/otel v1.21.0/go.mod h1:QZzNPQPm1zLX4gZK4cMi+71eaorMSGT3A4znnUvNNEo=
go.opentelemetry.io/otel/metric v1.21.0 h1:tlYWfeo+Bocx5kLEloTjbcDwBuELRrIFxwdQ36PlJu4=
go.opentelemetry.io/otel/metric v1.21.0/go.mod h1:o1p3CA8nNHW8j5yuQLdc1eeqEaPfzug24uvsyIEJRWM=
go.opentelemetry.io/otel/trace v1.21.0 h1:WD9i5gzvoUPuXIXH24ZNBudiarZDKuekPqi/E8fpfLc=
go.opentelemetry.io/otel/trace v1.21.0/go.mod h1:LGbsEB0f9LGjN+OZaQQ26sohbOmiMR+BaslueVtS/qQ=
go.uber.org/atomic v1.6.0/go.mod h1:sABNBOSYdrvTF6hTgEIbc7YasKWGhgEQZyfxyTvoXHQ=
go.uber.org/atomic v1.7.0/go.mod h1:fEN4uk6kAWBTFdckzkM89CLk9XfWZrxpCo0nPH17wJc=
go.uber.org/atomic v1.11.0 h1:ZvwS0R+56ePWxUNi+Atn9dWONBPp/AUETXlHW0DxSjE=
go.uber.org/atomic v1.11.0/go.mod h1:LUxbIzbOniOlMKjJjyPfpl4v+PKK2cNJn91OQbhoJI0=
go.uber.org/goleak v1.1.11-0.20210813005559-691160354723/go.mod h1:cwTWslyiVhfpKIDGSZEM2HlOvcqm+tG4zioyIeLoqMQ=
go.uber.org/goleak v1.2.0 h1:xqgm/S+aQvhWFTtR0XK3Jvg7z8kGV8P4X14IzwN3Eqk=
go.uber.org/goleak v1.2.0/go.mod h1:XJYK+MuIchqpmGmUSAzotztawfKvYLUIgg7guXrwVUo=
go.uber.org/multierr v1.5.0/go.mod h1:FeouvMocqHpRaaGuG9EjoKcStLC43Zu/fmqdUMPcKYU=
go.uber.org/multierr v1.6.0/go.mod h1:cdWPpRnG4AhwMwsgIHip0KRBQjJy5kYEpYjJxpXp9iU=
go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0=
go.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=
go.uber.org/tools v0.0.0-20190618225709-2cfd321de3ee/go.mod h1:vJERXedbb3MVM5f9Ejo0C68/HhF8uaILCdgjnY+goOA=
go.uber.org/zap v1.16.0/go.mod h1:MA8QOfq0BHJwdXa996Y4dYkAqRKB8/1K1QMMZVaNZjQ=
go.uber.org/zap v1.19.1/go.mod h1:j3DNczoxDZroyBnOT1L/Q79cfUMGZxlv/9dzN7SM1rI=
go.uber.org/zap v1.26.0 h1:sI7k6L95XOKS281NhVKOFCUNIvv9e0w4BF8N3u+tCRo=
go.uber.org/zap v1.26.0/go.mod h1:dtElttAiwGvoJ/vj4IwHBS/gXsEu/pZ50mUIRWuG0so=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20190510104115-cbcb75029529/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
golang.org/x/crypto v0.12.0/go.mod h1:NF0Gs7EO5K4qLn+Ylc+fih8BSTeIjAP05siRnAh98yw=
golang.org/x/crypto v0.38.0 h1:jt+WWG8IZlBnVbomuhg2Mdq0+BBQaHbtqHEFEigjUV8=
golang.org/x/crypto v0.38.0/go.mod h1:MvrbAqul58NNYPKnOra203SB9vpuZW0e+RRZV+Ggqjw=
golang.org/x/exp v0.0.0-20231110203233-9a3e6036ecaa h1:FRnLl4eNAQl8hwxVVC17teOw8kdjVDVAiFMtgUdTSRQ=
golang.org/x/exp v0.0.0-20231110203233-9a3e6036ecaa/go.mod h1:zk2irFbV9DP96SEBUUAy67IdHUaZuSnrz1n472HUCLE=
golang.org/x/lint v0.0.0-20190930215403-16217165b5de/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc=
golang.org/x/mod v0.0.0-20190513183733-4bf6d317e70e/go.mod h1:mXi4GBBbnImb6dmsKGUJ2LatrhH/nqhxcFungHvyanc=
golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
golang.org/x/mod v0.4.2/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=
golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
golang.org/x/mod v0.17.0 h1:zY54UmvipHiNd+pm+m0x9KhZ9hl1/7QNMyxXbc6ICqA=
golang.org/x/mod v0.17.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c=
golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20200226121028-0de0cce0169b/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU=
golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
golang.org/x/net v0.0.0-20210405180319-a5a99cb37ef4/go.mod h1:p54w0d4576C0XHj96bSt6lcn1PtDYWL6XObtHCRCNQM=
golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c=
golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs=
golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg=
golang.org/x/net v0.23.0 h1:7EYJ93RZ9vYSZAIb2x3lnuvqO5zneoD6IvWjuhfxjTs=
golang.org/x/net v0.23.0/go.mod h1:JKghWKKOSdJwpW2GEx0Ja7fmaKnMsbu+MWVZTokSYmg=
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.14.0 h1:woo0S4Yywslg6hp4eUFjTVOyKt0RookbpAHG4c1HmhQ=
golang.org/x/sync v0.14.0/go.mod h1:1dzgHSNfp02xaA81J2MS99Qcpr2w7fw1gpm99rleRqA=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210330210617-4fbd30eecc44/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210510120138-977fb7262007/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20210630005230-0f9fa26af87c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220412211240-33da011f77ad/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.11.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.33.0 h1:q3i8TbbEz+JRD9ywIRlyRAQbM0qF7hu24q3teo2hbuw=
golang.org/x/sys v0.33.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k=
golang.org/x/term v0.8.0/go.mod h1:xPskH00ivmX89bAKVGSKKtLOWNx2+17Eiy94tnKShWo=
golang.org/x/term v0.11.0/go.mod h1:zC9APTIj3jG3FdV/Ons+XE1riIZXG4aZ4GTHiPZJPIU=
golang.org/x/term v0.32.0 h1:DR4lr0TjUs3epypdhTOkMmuF5CDFJ/8pOnbzMZPQ7bg=
golang.org/x/term v0.32.0/go.mod h1:uZG1FhGx848Sqfsq4/DlJr3xGGsYMu/L5GW4abiaEPQ=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
golang.org/x/text v0.3.8/go.mod h1:E6s5w1FMmriuDzIBO73fBruAKo1PCIq6d2Q6DHfQ8WQ=
golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=
golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8=
golang.org/x/text v0.12.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE=
golang.org/x/text v0.25.0 h1:qVyWApTSYLk/drJRO5mDlNYskwQznZmkpV2c8q9zls4=
golang.org/x/text v0.25.0/go.mod h1:WEdwpYrmk1qmdHvhkSTNPm3app7v4rsT8F2UD6+VHIA=
golang.org/x/time v0.3.0 h1:rg5rLMjNzMS1RkNLzCG38eapWhnYLFYXDXj2gOlr8j4=
golang.org/x/time v0.3.0/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs=
golang.org/x/tools v0.0.0-20190328211700-ab21143f2384/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs=
golang.org/x/tools v0.0.0-20190621195816-6e04913cbbac/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc=
golang.org/x/tools v0.0.0-20191029041327-9cc4af7d6b2c/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/tools v0.0.0-20191029190741-b9c20aec41a5/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/tools v0.0.0-20200619180055-7c47624df98f/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE=
golang.org/x/tools v0.0.0-20210106214847-113979e3529a/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA=
golang.org/x/tools v0.1.5/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk=
golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc=
golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU=
golang.org/x/tools v0.21.1-0.20240508182429-e35e4ccd0d2d h1:vU5i/LfpvrRCpgM/VPfJLg5KjxD3E+hfT1SH+d9zLwg=
golang.org/x/tools v0.21.1-0.20240508182429-e35e4ccd0d2d/go.mod h1:aiJjzUbINMkxbQROHiO6hDPo2LHcIPhhQsa9DLh0yGk=
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20231012003039-104605ab7028 h1:+cNy6SZtPcJQH3LJVLOSmiC7MMxXNOb3PU/VUEz+EhU=
golang.org/x/xerrors v0.0.0-20231012003039-104605ab7028/go.mod h1:NDW/Ps6MPRej6fsCIbMTohpP40sJ/P/vI1MoTEGwX90=
google.golang.org/protobuf v1.33.0 h1:uNO2rsAINq/JlFpSdYEKIZ0uKD/R9cpdv0T+yoGwGmI=
google.golang.org/protobuf v1.33.0/go.mod h1:c6P6GXX6sHbq/GpV6MGZEdwhWPcYBgnhAHhKbcUYpos=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=
gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI=
gopkg.in/inf.v0 v0.9.1 h1:73M5CoZyi3ZLMOyDlQh031Cx6N9NDJ2Vvfl76EDAgDc=
gopkg.in/inf.v0 v0.9.1/go.mod h1:cWUDdTG/fYaXco+Dcufb5Vnc6Gp2YChqWtbxRZE0mXw=
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY=
gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gorm.io/driver/postgres v1.5.7 h1:8ptbNJTDbEmhdr62uReG5BGkdQyeasu/FZHxI0IMGnM=
gorm.io/driver/postgres v1.5.7/go.mod h1:3e019WlBaYI5o5LIdNV+LyxCMNtLOQETBXL2h4chKpA=
gorm.io/driver/sqlite v1.5.5 h1:7MDMtUZhV065SilG62E0MquljeArQZNfJnjd9i9gx3E=
gorm.io/driver/sqlite v1.5.5/go.mod h1:6NgQ7sQWAIFsPrJJl1lSNSu2TABh0ZZ/zm5fosATavE=
gorm.io/gorm v1.25.9 h1:wct0gxZIELDk8+ZqF/MVnHLkA1rvYlBWUMv2EdsK1g8=
gorm.io/gorm v1.25.9/go.mod h1:hbnx/Oo0ChWMn1BIhpy1oYozzpM15i4YPuHDmfYtwg8=
honnef.co/go/tools v0.0.1-2019.2.3/go.mod h1:a3bituU0lyd329TUQxRnasdCoJDkEUEAqEt0JzvZhAg=
lukechampine.com/blake3 v1.2.1 h1:YuqqRuaqsGV71BV/nm9xlI0MKUv4QC54jQnBChWbGnI=
lukechampine.com/blake3 v1.2.1/go.mod h1:0OFRp7fBtAylGVCO40o87sbupkyIGgbpv1+M1k1LM6k=

62
pkg/api/base.go Normal file
View File

@ -0,0 +1,62 @@
package api
import (
"context"
"fmt"
"net/http"
"time"
"github.com/aykhans/bsky-feedgen/pkg/api/handler"
"github.com/aykhans/bsky-feedgen/pkg/config"
"github.com/aykhans/bsky-feedgen/pkg/feed"
"github.com/aykhans/bsky-feedgen/pkg/logger"
)
func Run(
ctx context.Context,
apiConfig *config.APIConfig,
feeds []feed.Feed,
) error {
baseHandler, err := handler.NewBaseHandler(apiConfig.FeedgenHostname, apiConfig.ServiceDID)
if err != nil {
return err
}
feedHandler := handler.NewFeedHandler(feeds, apiConfig.FeedgenPublisherDID)
mux := http.NewServeMux()
mux.HandleFunc("GET /.well-known/did.json", baseHandler.GetWellKnownDIDDoc)
mux.HandleFunc("GET /xrpc/app.bsky.feed.describeFeedGenerator", feedHandler.DescribeFeeds)
mux.HandleFunc(
"GET /xrpc/app.bsky.feed.getFeedSkeleton",
feedHandler.GetFeedSkeleton,
)
httpServer := &http.Server{
Addr: fmt.Sprintf(":%d", apiConfig.APIPort),
Handler: mux,
}
listenerErrChan := make(chan error)
logger.Log.Info(fmt.Sprintf("Starting server on port %d", apiConfig.APIPort))
go func() {
listenerErrChan <- httpServer.ListenAndServe()
}()
select {
case err := <-listenerErrChan:
if err != nil && err != http.ErrServerClosed {
return fmt.Errorf("error while serving http: %v", err)
}
case <-ctx.Done():
shutdownCtx, shutdownCancel := context.WithTimeout(context.Background(), time.Second*10)
defer shutdownCancel()
if err := httpServer.Shutdown(shutdownCtx); err != nil {
return fmt.Errorf("error while shutting down http server: %v", err)
}
}
logger.Log.Info(fmt.Sprintf("Server on port %d stopped", apiConfig.APIPort))
return nil
}

49
pkg/api/handler/base.go Normal file
View File

@ -0,0 +1,49 @@
package handler
import (
"fmt"
"net/http"
"net/url"
"github.com/aykhans/bsky-feedgen/pkg/api/response"
"github.com/whyrusleeping/go-did"
)
type BaseHandler struct {
WellKnownDIDDoc did.Document
}
func NewBaseHandler(serviceEndpoint *url.URL, serviceDID *did.DID) (*BaseHandler, error) {
serviceID, err := did.ParseDID("#bsky_fg")
if err != nil {
return nil, fmt.Errorf("service ID parse error: %v", err)
}
return &BaseHandler{
WellKnownDIDDoc: did.Document{
Context: []string{did.CtxDIDv1},
ID: *serviceDID,
Service: []did.Service{
{
ID: serviceID,
Type: "BskyFeedGenerator",
ServiceEndpoint: serviceEndpoint.String(),
},
},
},
}, nil
}
type WellKnownDidResponse struct {
Context []string `json:"@context"`
ID string `json:"id"`
Service []did.Service `json:"service"`
}
func (handler *BaseHandler) GetWellKnownDIDDoc(w http.ResponseWriter, r *http.Request) {
response.JSON(w, 200, WellKnownDidResponse{
Context: handler.WellKnownDIDDoc.Context,
ID: handler.WellKnownDIDDoc.ID.String(),
Service: handler.WellKnownDIDDoc.Service,
})
}

101
pkg/api/handler/feed.go Normal file
View File

@ -0,0 +1,101 @@
package handler
import (
"context"
"net/http"
"strconv"
"strings"
"time"
"github.com/aykhans/bsky-feedgen/pkg/api/middleware"
"github.com/aykhans/bsky-feedgen/pkg/api/response"
"github.com/aykhans/bsky-feedgen/pkg/feed"
"github.com/aykhans/bsky-feedgen/pkg/types"
"github.com/aykhans/bsky-feedgen/pkg/utils"
"github.com/bluesky-social/indigo/api/bsky"
"github.com/whyrusleeping/go-did"
)
type FeedHandler struct {
feedsOutput []*bsky.FeedDescribeFeedGenerator_Feed
feedsMap map[string]feed.Feed
publisherDID *did.DID
}
func NewFeedHandler(feeds []feed.Feed, publisherDID *did.DID) *FeedHandler {
ctx := context.Background()
feedsMap := make(map[string]feed.Feed)
for _, feed := range feeds {
feedsMap[feed.GetName(ctx)] = feed
}
feedsOutput := make([]*bsky.FeedDescribeFeedGenerator_Feed, len(feeds))
for i, f := range feeds {
feedsOutput[i] = utils.ToPtr(f.Describe(ctx))
}
return &FeedHandler{
feedsOutput: feedsOutput,
feedsMap: feedsMap,
publisherDID: publisherDID,
}
}
func (handler *FeedHandler) DescribeFeeds(w http.ResponseWriter, r *http.Request) {
response.JSON(w, 200, bsky.FeedDescribeFeedGenerator_Output{
Did: handler.publisherDID.String(),
Feeds: handler.feedsOutput,
})
}
func (handler *FeedHandler) GetFeedSkeleton(w http.ResponseWriter, r *http.Request) {
userDID, _ := r.Context().Value(middleware.UserDIDKey).(string)
feedQuery := r.URL.Query().Get("feed")
if feedQuery == "" {
response.JSON(w, 400, response.M{"error": "feed query parameter is required"})
return
}
feedNameStartingIndex := strings.LastIndex(feedQuery, "/")
if feedNameStartingIndex == -1 {
response.JSON(w, 400, response.M{"error": "feed query parameter is invalid"})
}
feedName := feedQuery[feedNameStartingIndex+1:]
feed := handler.feedsMap[feedName]
if feed == nil {
response.JSON(w, 400, response.M{"error": "feed not found"})
return
}
limitQuery := r.URL.Query().Get("limit")
var limit int64 = 50
if limitQuery != "" {
parsedLimit, err := strconv.ParseInt(limitQuery, 10, 64)
if err == nil && parsedLimit >= 1 && parsedLimit <= 100 {
limit = parsedLimit
}
}
cursor := r.URL.Query().Get("cursor")
ctx, cancel := context.WithTimeout(context.Background(), time.Second*5)
defer cancel()
feedItems, newCursor, err := feed.GetPage(ctx, userDID, limit, cursor)
if err != nil {
if err == types.ErrInternal {
response.JSON500(w)
return
}
response.JSON(w, 400, response.M{"error": err.Error()})
return
}
response.JSON(w, 200, bsky.FeedGetFeedSkeleton_Output{
Feed: feedItems,
Cursor: newCursor,
})
}

View File

@ -0,0 +1,23 @@
package middleware
import (
"context"
"net/http"
)
const UserDIDKey ContextKey = "user_did"
func JWTAuthMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
authHeader := r.Header.Get("Authorization")
if authHeader == "" {
// No auth header, continue without authentication
next.ServeHTTP(w, r)
return
}
// TODO: Add auth verification
ctx := context.WithValue(r.Context(), UserDIDKey, "")
next.ServeHTTP(w, r.WithContext(ctx))
})
}

View File

@ -0,0 +1,3 @@
package middleware
type ContextKey string

27
pkg/api/response/json.go Normal file
View File

@ -0,0 +1,27 @@
package response
import (
"encoding/json"
"net/http"
"github.com/aykhans/bsky-feedgen/pkg/logger"
)
type M map[string]any
func JSON(w http.ResponseWriter, statusCode int, data any) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(statusCode)
if err := json.NewEncoder(w).Encode(data); err != nil {
logger.Log.Error("Failed to encode JSON response", "error", err)
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
}
}
func JSON500(w http.ResponseWriter) {
JSON(w, 500, M{"error": "Internal server error"})
}
func JSON404(w http.ResponseWriter) {
JSON(w, 404, M{"error": "Not found"})
}

24
pkg/api/response/text.go Normal file
View File

@ -0,0 +1,24 @@
package response
import (
"net/http"
"github.com/aykhans/bsky-feedgen/pkg/logger"
)
func Text(w http.ResponseWriter, statusCode int, content []byte) {
w.Header().Set("Content-Type", "text/plain")
w.WriteHeader(statusCode)
if _, err := w.Write(content); err != nil {
logger.Log.Error("Failed to write text response", "error", err)
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
}
}
func Text404(w http.ResponseWriter) {
Text(w, 404, []byte("Not found"))
}
func Text500(w http.ResponseWriter) {
Text(w, 500, []byte("Internal server error"))
}

70
pkg/config/api.go Normal file
View File

@ -0,0 +1,70 @@
package config
import (
"fmt"
"net/url"
"slices"
"github.com/aykhans/bsky-feedgen/pkg/types"
"github.com/aykhans/bsky-feedgen/pkg/utils"
"github.com/whyrusleeping/go-did"
)
type APIConfig struct {
FeedgenHostname *url.URL
ServiceDID *did.DID
FeedgenPublisherDID *did.DID
APIPort uint16
}
func NewAPIConfig() (*APIConfig, types.ErrMap) {
errs := make(types.ErrMap)
defaultHostname, _ := url.Parse("http://localhost")
feedgenHostname, err := utils.GetEnvOr("FEEDGEN_HOSTNAME", defaultHostname)
if err != nil {
errs["FEEDGEN_HOSTNAME"] = err
} else {
if !slices.Contains([]string{"", "http", "https"}, feedgenHostname.Scheme) {
errs["FEEDGEN_HOSTNAME"] = fmt.Errorf(
"invalid schema '%s' for FEEDGEN_HOSTNAME. Accepted schemas are: '', 'http', 'https'",
feedgenHostname.Scheme,
)
}
}
serviceDID, err := did.ParseDID("did:web:" + feedgenHostname.Hostname())
if err != nil {
errs["SERVICE_DID"] = fmt.Errorf("failed to parse service DID: %w", err)
}
defaultDID, _ := did.ParseDID("did:plc:development")
feedgenPublisherDID, err := utils.GetEnvOr("FEEDGEN_PUBLISHER_DID", &defaultDID)
if err != nil {
errs["FEEDGEN_PUBLISHER_DID"] = err
}
apiPort, err := utils.GetEnv[uint16]("API_PORT")
if err != nil {
errs["API_PORT"] = err
}
if len(errs) > 0 {
return nil, errs
}
if feedgenHostname.Scheme == "" {
if feedgenHostname.Host == "" {
feedgenHostname, _ = url.Parse("https://" + feedgenHostname.String())
} else {
feedgenHostname.Scheme = "https://"
}
}
return &APIConfig{
FeedgenHostname: feedgenHostname,
ServiceDID: &serviceDID,
FeedgenPublisherDID: feedgenPublisherDID,
APIPort: apiPort,
}, nil
}

40
pkg/config/consumer.go Normal file
View File

@ -0,0 +1,40 @@
package config
import (
"time"
"github.com/aykhans/bsky-feedgen/pkg/types"
"github.com/aykhans/bsky-feedgen/pkg/utils"
)
type ConsumerConfig struct {
PostMaxDate time.Duration
PostCollectionCutoffCronDelay time.Duration
PostCollectionCutoffCronMaxDocument int64
}
func NewConsumerConfig() (*ConsumerConfig, types.ErrMap) {
errs := make(types.ErrMap)
maxDate, err := utils.GetEnv[time.Duration]("POST_MAX_DATE")
if err != nil {
errs["POST_MAX_DATE"] = err
}
cronDelay, err := utils.GetEnv[time.Duration]("POST_COLLECTION_CUTOFF_CRON_DELAY")
if err != nil {
errs["POST_COLLECTION_CUTOFF_CRON_DELAY"] = err
}
cronMaxDocument, err := utils.GetEnv[int64]("POST_COLLECTION_CUTOFF_CRON_MAX_DOCUMENT")
if err != nil {
errs["POST_COLLECTION_CUTOFF_CRON_MAX_DOCUMENT"] = err
}
if len(errs) > 0 {
return nil, errs
}
return &ConsumerConfig{
PostMaxDate: maxDate,
PostCollectionCutoffCronDelay: cronDelay,
PostCollectionCutoffCronMaxDocument: cronMaxDocument,
}, nil
}

40
pkg/config/feedgen.go Normal file
View File

@ -0,0 +1,40 @@
package config
import (
"time"
"github.com/aykhans/bsky-feedgen/pkg/types"
"github.com/aykhans/bsky-feedgen/pkg/utils"
)
type FeedGenAzConfig struct {
CollectionMaxDocument int64
GeneratorCronDelay time.Duration
CutoffCronDelay time.Duration
}
func NewFeedGenAzConfig() (*FeedGenAzConfig, types.ErrMap) {
errs := make(types.ErrMap)
maxDocument, err := utils.GetEnv[int64]("FEED_AZ_COLLECTION_CUTOFF_CRON_MAX_DOCUMENT")
if err != nil {
errs["FEED_AZ_COLLECTION_CUTOFF_CRON_MAX_DOCUMENT"] = err
}
generatorCronDelay, err := utils.GetEnv[time.Duration]("FEED_AZ_GENERATER_CRON_DELAY")
if err != nil {
errs["FEED_AZ_GENERATER_CRON_DELAY"] = err
}
cutoffCronDelay, err := utils.GetEnv[time.Duration]("FEED_AZ_COLLECTION_CUTOFF_CRON_DELAY")
if err != nil {
errs["FEED_AZ_COLLECTION_CUTOFF_CRON_DELAY"] = err
}
if len(errs) > 0 {
return nil, errs
}
return &FeedGenAzConfig{
CollectionMaxDocument: maxDocument,
GeneratorCronDelay: generatorCronDelay,
CutoffCronDelay: cutoffCronDelay,
}, nil
}

46
pkg/config/mongodb.go Normal file
View File

@ -0,0 +1,46 @@
package config
import (
"github.com/aykhans/bsky-feedgen/pkg/types"
"github.com/aykhans/bsky-feedgen/pkg/utils"
)
const MongoDBBaseDB = "main"
type MongoDBConfig struct {
Host string
Port uint16
Username string
Password string
}
func NewMongoDBConfig() (*MongoDBConfig, types.ErrMap) {
errs := make(types.ErrMap)
host, err := utils.GetEnv[string]("MONGODB_HOST")
if err != nil {
errs["host"] = err
}
port, err := utils.GetEnv[uint16]("MONGODB_PORT")
if err != nil {
errs["port"] = err
}
username, err := utils.GetEnvOr("MONGODB_USERNAME", "")
if err != nil {
errs["username"] = err
}
password, err := utils.GetEnvOr("MONGODB_PASSWORD", "")
if err != nil {
errs["password"] = err
}
if len(errs) > 0 {
return nil, errs
}
return &MongoDBConfig{
Host: host,
Port: port,
Username: username,
Password: password,
}, nil
}

273
pkg/consumer/base.go Normal file
View File

@ -0,0 +1,273 @@
package consumer
import (
"bytes"
"context"
"fmt"
"net/http"
"net/url"
"strconv"
"strings"
"time"
"github.com/aykhans/bsky-feedgen/pkg/logger"
"github.com/aykhans/bsky-feedgen/pkg/storage/mongodb/collections"
"github.com/aykhans/bsky-feedgen/pkg/types"
"github.com/aykhans/bsky-feedgen/pkg/utils"
comatproto "github.com/bluesky-social/indigo/api/atproto"
"github.com/bluesky-social/indigo/api/bsky"
"github.com/bluesky-social/indigo/atproto/syntax"
"github.com/bluesky-social/indigo/events/schedulers/parallel"
lexutil "github.com/bluesky-social/indigo/lex/util"
"github.com/bluesky-social/indigo/events"
"github.com/bluesky-social/indigo/repo"
"github.com/bluesky-social/indigo/repomgr"
"github.com/gorilla/websocket"
)
type CallbackData struct {
Sequence int64
DID syntax.DID
RecordKey syntax.RecordKey
Post bsky.FeedPost
}
type CallbackFunc func(int64, syntax.DID, syntax.RecordKey, bsky.FeedPost)
func RunFirehoseConsumer(
ctx context.Context,
relayHost string,
callbackFunc CallbackFunc,
cursor *int64,
) error {
dialer := websocket.DefaultDialer
u, err := url.Parse(relayHost)
if err != nil {
return fmt.Errorf("invalid relayHost URI: %w", err)
}
u.Path = "xrpc/com.atproto.sync.subscribeRepos"
if cursor != nil {
q := url.Values{}
q.Set("cursor", strconv.FormatInt(*cursor, 10))
u.RawQuery = q.Encode()
}
logger.Log.Info("subscribing to repo event stream", "upstream", relayHost)
con, _, err := dialer.Dial(u.String(), http.Header{
"User-Agent": []string{"Firehose-Consumer"},
})
if err != nil {
return fmt.Errorf("subscribing to firehose failed (dialing): %w", err)
}
rsc := &events.RepoStreamCallbacks{
RepoCommit: func(evt *comatproto.SyncSubscribeRepos_Commit) error {
return HandleRepoCommit(ctx, evt, callbackFunc)
},
}
var scheduler events.Scheduler
parallelism := 8
scheduler = parallel.NewScheduler(
parallelism,
100_000,
relayHost,
rsc.EventHandler,
)
logger.Log.Info("firehose scheduler configured", "workers", parallelism)
err = events.HandleRepoStream(ctx, con, scheduler, logger.Log)
if err != nil {
return fmt.Errorf("repoStream error: %v", err)
}
return nil
}
func HandleRepoCommit(
ctx context.Context,
evt *comatproto.SyncSubscribeRepos_Commit,
postCallback CallbackFunc,
) error {
localLogger := logger.Log.With("event", "commit", "did", evt.Repo, "rev", evt.Rev, "seq", evt.Seq)
if evt.TooBig {
localLogger.Warn("skipping tooBig events for now")
return nil
}
did, err := syntax.ParseDID(evt.Repo)
if err != nil {
localLogger.Error("bad DID syntax in event", "err", err)
return nil
}
rr, err := repo.ReadRepoFromCar(ctx, bytes.NewReader(evt.Blocks))
if err != nil {
localLogger.Error("failed to read repo from car", "err", err)
return nil
}
for _, op := range evt.Ops {
localLogger = localLogger.With("eventKind", op.Action, "path", op.Path)
collection, rkey, err := syntax.ParseRepoPath(op.Path)
if err != nil {
localLogger.Error("invalid path in repo op")
return nil
}
ek := repomgr.EventKind(op.Action)
switch ek {
case repomgr.EvtKindCreateRecord, repomgr.EvtKindUpdateRecord:
// read the record bytes from blocks, and verify CID
rc, recordCBOR, err := rr.GetRecordBytes(ctx, op.Path)
if err != nil {
localLogger.Error("reading record from event blocks (CAR)", "err", err)
continue
}
if op.Cid == nil || lexutil.LexLink(rc) != *op.Cid {
localLogger.Error("mismatch between commit op CID and record block", "recordCID", rc, "opCID", op.Cid)
continue
}
switch collection {
case "app.bsky.feed.post":
var post bsky.FeedPost
if err := post.UnmarshalCBOR(bytes.NewReader(*recordCBOR)); err != nil {
localLogger.Error("failed to parse app.bsky.feed.post record", "err", err)
continue
}
postCallback(evt.Seq, did, rkey, post)
}
}
}
return nil
}
func ConsumeAndSaveToMongoDB(
ctx context.Context,
postCollection *collections.PostCollection,
relayHost string,
cursorOption types.ConsumerCursor,
oldestPostDuration time.Duration,
batchFlushTime time.Duration,
) error {
firehoseDataChan := make(chan CallbackData, 500)
localCtx, cancel := context.WithCancel(ctx)
defer cancel()
var sequenceCursor *int64
switch cursorOption {
case types.ConsumerCursorLastConsumed:
var err error
sequenceCursor, err = postCollection.GetMaxSequence(ctx)
if err != nil {
return err
}
case types.ConsumerCursorFirstStream:
sequenceCursor = utils.ToPtr[int64](0)
case types.ConsumerCursorCurrentStream:
sequenceCursor = nil
}
go func() {
defer cancel()
for {
err := RunFirehoseConsumer(
ctx,
relayHost,
func(sequence int64, did syntax.DID, recordKey syntax.RecordKey, post bsky.FeedPost) {
firehoseDataChan <- CallbackData{sequence, did, recordKey, post}
},
sequenceCursor,
)
if err != nil {
if ctx.Err() != nil {
break
}
logger.Log.Error(err.Error())
if !strings.HasPrefix(err.Error(), "repoStream error") {
break
}
}
sequenceCursor, err = postCollection.GetMaxSequence(ctx)
if err != nil {
logger.Log.Error(err.Error())
break
}
}
}()
postBatch := []*collections.Post{}
ticker := time.NewTicker(batchFlushTime)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
logger.Log.Info("consumer shutting down")
return nil
case <-localCtx.Done():
return nil
case data := <-firehoseDataChan:
facets := &collections.Facets{}
for _, facet := range data.Post.Facets {
for _, feature := range facet.Features {
if feature.RichtextFacet_Mention != nil {
facets.Mentions = append(facets.Mentions, feature.RichtextFacet_Mention.Did)
}
if feature.RichtextFacet_Link != nil {
facets.Links = append(facets.Links, feature.RichtextFacet_Link.Uri)
}
if feature.RichtextFacet_Tag != nil {
facets.Tags = append(facets.Tags, feature.RichtextFacet_Tag.Tag)
}
}
}
reply := &collections.Reply{}
if data.Post.Reply != nil {
if data.Post.Reply.Root != nil {
reply.RootURI = data.Post.Reply.Root.Uri
}
if data.Post.Reply.Parent != nil {
reply.ParentURI = data.Post.Reply.Parent.Uri
}
}
createdAt, _ := time.Parse(time.RFC3339, data.Post.CreatedAt)
if createdAt.After(time.Now().UTC().Add(-oldestPostDuration)) {
postItem := &collections.Post{
ID: fmt.Sprintf("%s/%s", data.DID, data.RecordKey),
Sequence: data.Sequence,
DID: data.DID.String(),
RecordKey: data.RecordKey.String(),
CreatedAt: createdAt,
Langs: data.Post.Langs,
Tags: data.Post.Tags,
Text: data.Post.Text,
Facets: facets,
Reply: reply,
}
postBatch = append(postBatch, postItem)
}
case <-ticker.C:
if len(postBatch) > 0 {
// logger.Log.Info("flushing post batch", "count", len(postBatch))
err := postCollection.Insert(ctx, true, postBatch...)
if err != nil {
return fmt.Errorf("mongodb post insert error: %v", err)
}
postBatch = []*collections.Post{} // Clear batch after insert
}
}
}
}

80
pkg/feed/az.go Normal file
View File

@ -0,0 +1,80 @@
package feed
import (
"context"
"fmt"
"strconv"
"github.com/aykhans/bsky-feedgen/pkg/logger"
"github.com/aykhans/bsky-feedgen/pkg/storage/mongodb/collections"
"github.com/aykhans/bsky-feedgen/pkg/types"
"github.com/aykhans/bsky-feedgen/pkg/utils"
"github.com/bluesky-social/indigo/api/bsky"
"github.com/whyrusleeping/go-did"
)
type FeedAz struct {
name string
did *did.DID
feedAzCollection *collections.FeedAzCollection
}
func NewFeedAz(name string, publisherDID *did.DID, feedAzCollection *collections.FeedAzCollection) *FeedAz {
return &FeedAz{
name: name,
did: publisherDID,
feedAzCollection: feedAzCollection,
}
}
func (f FeedAz) GetName(_ context.Context) string {
return f.name
}
func (f *FeedAz) Describe(_ context.Context) bsky.FeedDescribeFeedGenerator_Feed {
return bsky.FeedDescribeFeedGenerator_Feed{
Uri: "at://" + f.did.String() + "/app.bsky.feed.generator/" + f.name,
}
}
func (f *FeedAz) GetPage(
ctx context.Context,
_ string,
limit int64,
cursor string,
) ([]*bsky.FeedDefs_SkeletonFeedPost, *string, error) {
var cursorInt int64 = 0
if cursor != "" {
var err error
cursorInt, err = strconv.ParseInt(cursor, 10, 64)
if err != nil {
return nil, nil, fmt.Errorf("cursor is not an integer: %w", err)
}
}
feedAzItems, err := f.feedAzCollection.GetByCreatedAt(ctx, cursorInt, limit+1)
if err != nil {
logger.Log.Error("failed to get feedAzCollection items", "error", err)
return nil, nil, types.ErrInternal
}
var newCursor *string
if feedAzItemsLen := int64(len(feedAzItems)); limit >= feedAzItemsLen {
posts := make([]*bsky.FeedDefs_SkeletonFeedPost, feedAzItemsLen)
for i, feedItem := range feedAzItems {
posts[i] = &bsky.FeedDefs_SkeletonFeedPost{
Post: "at://" + feedItem.DID + "/app.bsky.feed.post/" + feedItem.RecordKey,
}
}
return posts, newCursor, nil
} else {
posts := make([]*bsky.FeedDefs_SkeletonFeedPost, feedAzItemsLen-1)
for i, feedItem := range feedAzItems[:feedAzItemsLen-1] {
posts[i] = &bsky.FeedDefs_SkeletonFeedPost{
Post: "at://" + feedItem.DID + "/app.bsky.feed.post/" + feedItem.RecordKey,
}
}
return posts, utils.ToPtr(strconv.FormatInt(cursorInt+limit, 10)), nil
}
}

13
pkg/feed/base.go Normal file
View File

@ -0,0 +1,13 @@
package feed
import (
"context"
"github.com/bluesky-social/indigo/api/bsky"
)
type Feed interface {
GetPage(ctx context.Context, userDID string, limit int64, cursor string) (feedPosts []*bsky.FeedDefs_SkeletonFeedPost, newCursor *string, err error)
GetName(ctx context.Context) string
Describe(ctx context.Context) bsky.FeedDescribeFeedGenerator_Feed
}

130
pkg/generator/az.go Normal file
View File

@ -0,0 +1,130 @@
package generator
import (
"context"
"fmt"
"regexp"
"slices"
"github.com/aykhans/bsky-feedgen/pkg/storage/mongodb/collections"
"github.com/aykhans/bsky-feedgen/pkg/types"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
var azValidUsers []string = []string{
"did:plc:jbt4qi6psd7rutwzedtecsq7",
"did:plc:yzgdpxsklrmfgqmjghdvw3ti",
"did:plc:cs2cbzojm6hmx5lfxiuft3mq",
}
type FeedGeneratorAz struct {
postCollection *collections.PostCollection
feedAzCollection *collections.FeedAzCollection
textRegex *regexp.Regexp
}
func NewFeedGeneratorAz(
postCollection *collections.PostCollection,
feedAzCollection *collections.FeedAzCollection,
) *FeedGeneratorAz {
return &FeedGeneratorAz{
postCollection: postCollection,
feedAzCollection: feedAzCollection,
textRegex: regexp.MustCompile("(?i)(azerbaijan|azərbaycan|aзербайджан|azerbaycan)"),
}
}
func (generator *FeedGeneratorAz) Start(ctx context.Context, cursorOption types.GeneratorCursor, batchSize int) error {
var mongoCursor *mongo.Cursor
switch cursorOption {
case types.GeneratorCursorLastGenerated:
sequenceCursor, err := generator.feedAzCollection.GetMaxSequence(ctx)
if err != nil {
return err
}
if sequenceCursor == nil {
mongoCursor, err = generator.postCollection.Collection.Find(
ctx,
bson.D{},
options.Find().SetSort(bson.D{{Key: "sequence", Value: 1}}),
)
} else {
mongoCursor, err = generator.postCollection.Collection.Find(
ctx,
bson.M{"sequence": bson.M{"$gt": *sequenceCursor}},
)
}
if err != nil {
return err
}
case types.GeneratorCursorFirstPost:
var err error
mongoCursor, err = generator.postCollection.Collection.Find(
ctx,
bson.D{},
options.Find().SetSort(bson.D{{Key: "sequence", Value: 1}}),
)
if err != nil {
return err
}
}
defer func() { _ = mongoCursor.Close(ctx) }()
feedAzBatch := []*collections.FeedAz{}
for mongoCursor.Next(ctx) {
var doc *collections.Post
if err := mongoCursor.Decode(&doc); err != nil {
return fmt.Errorf("mongodb cursor decode error: %v", err)
}
if generator.IsValid(doc) == false {
continue
}
feedAzBatch = append(
feedAzBatch,
&collections.FeedAz{
ID: doc.ID,
Sequence: doc.Sequence,
DID: doc.DID,
RecordKey: doc.RecordKey,
CreatedAt: doc.CreatedAt,
},
)
if len(feedAzBatch)%batchSize == 0 {
err := generator.feedAzCollection.Insert(ctx, true, feedAzBatch...)
if err != nil {
return fmt.Errorf("insert FeedAz error: %v", err)
}
feedAzBatch = []*collections.FeedAz{}
}
}
if len(feedAzBatch) > 0 {
err := generator.feedAzCollection.Insert(ctx, true, feedAzBatch...)
if err != nil {
return fmt.Errorf("insert FeedAz error: %v", err)
}
}
return nil
}
func (generator *FeedGeneratorAz) IsValid(post *collections.Post) bool {
if post.Reply != nil && post.Reply.RootURI != post.Reply.ParentURI {
return false
}
if slices.Contains(azValidUsers, post.DID) || // Posts from always-valid users
(slices.Contains(post.Langs, "az") && len(post.Langs) < 3) || // Posts in Azerbaijani language with fewer than 3 languages
generator.textRegex.MatchString(post.Text) { // Posts containing Azerbaijan-related keywords
return true
}
return false
}

17
pkg/logger/base.go Normal file
View File

@ -0,0 +1,17 @@
package logger
import (
"log/slog"
"os"
)
var Log *slog.Logger
func init() {
Log = slog.New(
slog.NewTextHandler(
os.Stdout,
&slog.HandlerOptions{AddSource: true},
),
)
}

250
pkg/manage/base.go Normal file
View File

@ -0,0 +1,250 @@
// This package was primarily developed using LLM models and should NOT be considered reliable.
// The purpose of this package is to provide functionality for creating, updating, and deleting feed records on Bluesky, as no suitable tools were found for this purpose.
// If a reliable tool becomes available that can perform these operations, this package will be deprecated and the discovered tool will be referenced in the project instead.
package manage
import (
"context"
"fmt"
"os"
"time"
"github.com/aykhans/bsky-feedgen/pkg/utils"
"github.com/bluesky-social/indigo/api/atproto"
"github.com/bluesky-social/indigo/api/bsky"
lexutil "github.com/bluesky-social/indigo/lex/util"
"github.com/bluesky-social/indigo/xrpc"
)
const (
DefaultPDSHost = "https://bsky.social"
)
func NewClient(pdsHost *string) *xrpc.Client {
if pdsHost == nil {
pdsHost = utils.ToPtr(DefaultPDSHost)
}
return &xrpc.Client{
Host: *pdsHost,
}
}
func NewClientWithAuth(ctx context.Context, client *xrpc.Client, identifier, password string) (*xrpc.Client, error) {
if client == nil {
client = NewClient(nil)
}
auth, err := atproto.ServerCreateSession(ctx, client, &atproto.ServerCreateSession_Input{
Identifier: identifier,
Password: password,
})
if err != nil {
return nil, fmt.Errorf("failed to create auth session: %v", err)
}
client.Auth = &xrpc.AuthInfo{
AccessJwt: auth.AccessJwt,
RefreshJwt: auth.RefreshJwt,
Did: auth.Did,
Handle: auth.Handle,
}
return client, nil
}
func uploadBlob(ctx context.Context, clientWithAuth *xrpc.Client, avatarPath string) (*atproto.RepoUploadBlob_Output, error) {
if clientWithAuth == nil {
return nil, fmt.Errorf("client can't be nil")
}
if clientWithAuth.Auth == nil {
return nil, fmt.Errorf("client auth can't be nil")
}
avatarFile, err := os.Open(avatarPath)
if err != nil {
return nil, fmt.Errorf("failed to open avatar file: %v", err)
}
defer func() { _ = avatarFile.Close() }()
uploadResp, err := atproto.RepoUploadBlob(ctx, clientWithAuth, avatarFile)
if err != nil {
return nil, fmt.Errorf("failed to upload avatar: %v", err)
}
return uploadResp, nil
}
func GetFeedGenerator(ctx context.Context, clientWithAuth *xrpc.Client, keyName string) (*atproto.RepoGetRecord_Output, error) {
if clientWithAuth == nil {
return nil, fmt.Errorf("client can't be nil")
}
if clientWithAuth.Auth == nil {
return nil, fmt.Errorf("client auth can't be nil")
}
record, err := atproto.RepoGetRecord(
ctx,
clientWithAuth,
"",
"app.bsky.feed.generator",
clientWithAuth.Auth.Did,
keyName,
)
if err != nil {
return nil, fmt.Errorf("failed to get axisting feed generator: %v", err)
}
return record, nil
}
func CreateFeedGenerator(
ctx context.Context,
clientWithAuth *xrpc.Client,
displayName string,
description *string,
avatarPath *string,
did string,
keyName string,
) error {
if clientWithAuth == nil {
return fmt.Errorf("client can't be nil")
}
if clientWithAuth.Auth == nil {
return fmt.Errorf("client auth can't be nil")
}
var avatarBlob *lexutil.LexBlob
if avatarPath != nil {
uploadResp, err := uploadBlob(ctx, clientWithAuth, *avatarPath)
if err != nil {
return err
}
avatarBlob = uploadResp.Blob
}
record := bsky.FeedGenerator{
DisplayName: displayName,
Description: description,
Avatar: avatarBlob,
Did: did,
CreatedAt: time.Now().Format(time.RFC3339Nano),
}
wrappedRecord := &lexutil.LexiconTypeDecoder{
Val: &record,
}
_, err := atproto.RepoCreateRecord(ctx, clientWithAuth, &atproto.RepoCreateRecord_Input{
Collection: "app.bsky.feed.generator",
Repo: clientWithAuth.Auth.Did, // Your DID (the one creating the record)
Record: wrappedRecord,
Rkey: &keyName,
})
if err != nil {
return fmt.Errorf("failed to create feed generator: %v", err)
}
return nil
}
func UpdateFeedGenerator(
ctx context.Context,
clientWithAuth *xrpc.Client,
displayName *string,
description *string,
avatarPath *string,
did *string,
keyName string,
) error {
if clientWithAuth == nil {
return fmt.Errorf("client can't be nil")
}
if clientWithAuth.Auth == nil {
return fmt.Errorf("client auth can't be nil")
}
existingRecord, err := GetFeedGenerator(ctx, clientWithAuth, keyName)
if err != nil {
return fmt.Errorf("failed to get axisting feed generator: %v", err)
}
if existingRecord != nil && existingRecord.Value != nil {
if existingFeedgen, ok := existingRecord.Value.Val.(*bsky.FeedGenerator); ok {
if avatarPath != nil {
uploadResp, err := uploadBlob(ctx, clientWithAuth, *avatarPath)
if err != nil {
return err
}
existingFeedgen.Avatar = uploadResp.Blob
}
if displayName != nil {
existingFeedgen.DisplayName = *displayName
}
if description != nil {
existingFeedgen.Description = description
}
if did != nil {
existingFeedgen.Did = *did
}
wrappedExistingFeedgen := &lexutil.LexiconTypeDecoder{
Val: &bsky.FeedGenerator{
DisplayName: existingFeedgen.DisplayName,
Description: existingFeedgen.Description,
Did: existingFeedgen.Did,
Avatar: existingFeedgen.Avatar,
CreatedAt: existingFeedgen.CreatedAt,
},
}
_, err := atproto.RepoPutRecord(ctx, clientWithAuth, &atproto.RepoPutRecord_Input{
Collection: "app.bsky.feed.generator",
Repo: clientWithAuth.Auth.Did, // Your DID
Rkey: keyName, // The Rkey of the record to update
Record: wrappedExistingFeedgen,
SwapRecord: existingRecord.Cid,
})
if err != nil {
return fmt.Errorf("failed to update feed generator: %v", err)
}
} else {
return fmt.Errorf("feed generator not found")
}
}
return nil
}
func DeleteFeedGenerator(
ctx context.Context,
clientWithAuth *xrpc.Client,
keyName string,
) error {
if clientWithAuth == nil {
return fmt.Errorf("client can't be nil")
}
if clientWithAuth.Auth == nil {
return fmt.Errorf("client auth can't be nil")
}
f, err := atproto.RepoDeleteRecord(ctx, clientWithAuth, &atproto.RepoDeleteRecord_Input{
Collection: "app.bsky.feed.generator",
Repo: clientWithAuth.Auth.Did,
Rkey: keyName,
})
if err != nil {
return fmt.Errorf("failed to delete feed generator: %v", err)
}
if f.Commit == nil {
return fmt.Errorf("feed generator not found")
}
return nil
}

View File

@ -0,0 +1,194 @@
package collections
import (
"context"
"time"
"github.com/aykhans/bsky-feedgen/pkg/config"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
type FeedAzCollection struct {
Collection *mongo.Collection
}
func NewFeedAzCollection(client *mongo.Client) (*FeedAzCollection, error) {
client.Database(config.MongoDBBaseDB).Collection("")
coll := client.Database(config.MongoDBBaseDB).Collection("feed_az")
_, err := coll.Indexes().CreateMany(
context.Background(),
[]mongo.IndexModel{
{
Keys: bson.D{{Key: "sequence", Value: -1}},
},
{
Keys: bson.D{{Key: "created_at", Value: -1}},
},
},
)
if err != nil {
return nil, err
}
return &FeedAzCollection{Collection: coll}, nil
}
type FeedAz struct {
ID string `bson:"_id"`
Sequence int64 `bson:"sequence"`
DID string `bson:"did"`
RecordKey string `bson:"record_key"`
CreatedAt time.Time `bson:"created_at"`
}
func (f FeedAzCollection) GetByCreatedAt(ctx context.Context, skip int64, limit int64) ([]*FeedAz, error) {
cursor, err := f.Collection.Find(
ctx, bson.D{},
options.Find().
SetSort(bson.D{{Key: "created_at", Value: -1}}).
SetSkip(skip).
SetLimit(limit),
)
if err != nil {
return nil, err
}
defer func() { _ = cursor.Close(ctx) }()
var feedAzItems []*FeedAz
if err = cursor.All(ctx, &feedAzItems); err != nil {
return nil, err
}
return feedAzItems, nil
}
func (f FeedAzCollection) GetMaxSequence(ctx context.Context) (*int64, error) {
pipeline := mongo.Pipeline{
{
{Key: "$group", Value: bson.D{
{Key: "_id", Value: nil},
{Key: "maxSequence", Value: bson.D{
{Key: "$max", Value: "$sequence"},
},
},
},
},
},
}
cursor, err := f.Collection.Aggregate(ctx, pipeline)
if err != nil {
return nil, err
}
defer func() { _ = cursor.Close(ctx) }()
var result struct {
MaxSequence int64 `bson:"maxSequence"`
}
if cursor.Next(ctx) {
if err := cursor.Decode(&result); err != nil {
return nil, err
}
return &result.MaxSequence, err
}
return nil, nil
}
func (f FeedAzCollection) Insert(ctx context.Context, overwrite bool, feedAz ...*FeedAz) error {
switch len(feedAz) {
case 0:
return nil
case 1:
if overwrite == false {
_, err := f.Collection.InsertOne(ctx, feedAz[0])
return err
}
_, err := f.Collection.ReplaceOne(
ctx,
bson.M{"_id": feedAz[0].ID},
feedAz[0],
options.Replace().SetUpsert(true),
)
return err
default:
if overwrite == false {
documents := make([]any, len(feedAz))
for i, feed := range feedAz {
documents[i] = feed
}
_, err := f.Collection.InsertMany(ctx, documents)
return err
}
var models []mongo.WriteModel
for _, feed := range feedAz {
filter := bson.M{"_id": feed.ID}
model := mongo.NewReplaceOneModel().
SetFilter(filter).
SetReplacement(feed).
SetUpsert(true)
models = append(models, model)
}
opts := options.BulkWrite().SetOrdered(false)
_, err := f.Collection.BulkWrite(ctx, models, opts)
if err != nil {
return err
}
return nil
}
}
func (f FeedAzCollection) CutoffByCount(
ctx context.Context,
maxDocumentCount int64,
) (int64, error) {
count, err := f.Collection.CountDocuments(ctx, bson.M{})
if err != nil {
return 0, err
}
if count <= maxDocumentCount {
return 0, nil
}
deleteCount := count - maxDocumentCount
findOpts := options.Find().
SetSort(bson.D{{Key: "created_at", Value: 1}}).
SetLimit(deleteCount)
cursor, err := f.Collection.Find(ctx, bson.M{}, findOpts)
if err != nil {
return 0, err
}
defer func() { _ = cursor.Close(ctx) }()
var docsToDelete []bson.M
if err = cursor.All(ctx, &docsToDelete); err != nil {
return 0, err
}
if len(docsToDelete) == 0 {
return 0, nil
}
ids := make([]any, len(docsToDelete))
for i := range docsToDelete {
ids[i] = docsToDelete[i]["_id"]
}
result, err := f.Collection.DeleteMany(ctx, bson.M{"_id": bson.M{"$in": ids}})
if err != nil {
return 0, err
}
return result.DeletedCount, nil
}

View File

@ -0,0 +1,183 @@
package collections
import (
"context"
"time"
"github.com/aykhans/bsky-feedgen/pkg/config"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
type PostCollection struct {
Collection *mongo.Collection
}
func NewPostCollection(client *mongo.Client) (*PostCollection, error) {
client.Database(config.MongoDBBaseDB).Collection("")
coll := client.Database(config.MongoDBBaseDB).Collection("post")
_, err := coll.Indexes().CreateOne(
context.Background(),
mongo.IndexModel{
Keys: bson.D{{Key: "sequence", Value: -1}},
},
)
if err != nil {
return nil, err
}
return &PostCollection{Collection: coll}, nil
}
type Post struct {
ID string `bson:"_id"`
Sequence int64 `bson:"sequence"`
DID string `bson:"did"`
RecordKey string `bson:"record_key"`
CreatedAt time.Time `bson:"created_at"`
Langs []string `bson:"langs"`
Tags []string `bson:"tags"`
Text string `bson:"text"`
Facets *Facets `bson:"facets"`
Reply *Reply `bson:"reply"`
}
type Facets struct {
Tags []string `bson:"tags"`
Links []string `bson:"links"`
Mentions []string `bson:"mentions"`
}
type Reply struct {
RootURI string `bson:"root_uri"`
ParentURI string `bson:"parent_uri"`
}
func (p PostCollection) CutoffByCount(
ctx context.Context,
maxDocumentCount int64,
) (int64, error) {
count, err := p.Collection.CountDocuments(ctx, bson.M{})
if err != nil {
return 0, err
}
if count <= maxDocumentCount {
return 0, nil
}
deleteCount := count - maxDocumentCount
findOpts := options.Find().
SetSort(bson.D{{Key: "created_at", Value: 1}}).
SetLimit(deleteCount)
cursor, err := p.Collection.Find(ctx, bson.M{}, findOpts)
if err != nil {
return 0, err
}
defer func() { _ = cursor.Close(ctx) }()
var docsToDelete []bson.M
if err = cursor.All(ctx, &docsToDelete); err != nil {
return 0, err
}
if len(docsToDelete) == 0 {
return 0, nil
}
ids := make([]any, len(docsToDelete))
for i := range docsToDelete {
ids[i] = docsToDelete[i]["_id"]
}
result, err := p.Collection.DeleteMany(ctx, bson.M{"_id": bson.M{"$in": ids}})
if err != nil {
return 0, err
}
return result.DeletedCount, nil
}
func (p PostCollection) GetMaxSequence(ctx context.Context) (*int64, error) {
pipeline := mongo.Pipeline{
{
{Key: "$group", Value: bson.D{
{Key: "_id", Value: nil},
{Key: "maxSequence", Value: bson.D{
{Key: "$max", Value: "$sequence"},
},
},
},
},
},
}
cursor, err := p.Collection.Aggregate(ctx, pipeline)
if err != nil {
return nil, err
}
defer func() { _ = cursor.Close(ctx) }()
var result struct {
MaxSequence int64 `bson:"maxSequence"`
}
if cursor.Next(ctx) {
if err := cursor.Decode(&result); err != nil {
return nil, err
}
return &result.MaxSequence, err
}
return nil, nil
}
func (p PostCollection) Insert(ctx context.Context, overwrite bool, posts ...*Post) error {
switch len(posts) {
case 0:
return nil
case 1:
if overwrite == false {
_, err := p.Collection.InsertOne(ctx, posts[0])
return err
}
_, err := p.Collection.ReplaceOne(
ctx,
bson.M{"_id": posts[0].ID},
posts[0],
options.Replace().SetUpsert(true),
)
return err
default:
if overwrite == false {
documents := make([]any, len(posts))
for i, post := range posts {
documents[i] = post
}
_, err := p.Collection.InsertMany(ctx, documents)
return err
}
var models []mongo.WriteModel
for _, post := range posts {
filter := bson.M{"_id": post.ID}
model := mongo.NewReplaceOneModel().
SetFilter(filter).
SetReplacement(post).
SetUpsert(true)
models = append(models, model)
}
opts := options.BulkWrite().SetOrdered(false)
_, err := p.Collection.BulkWrite(ctx, models, opts)
if err != nil {
return err
}
return nil
}
}

39
pkg/storage/mongodb/db.go Normal file
View File

@ -0,0 +1,39 @@
package mongodb
import (
"context"
"fmt"
"time"
"github.com/aykhans/bsky-feedgen/pkg/config"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
func NewDB(ctx context.Context, dbConfig *config.MongoDBConfig) (*mongo.Client, error) {
clientOptions := options.Client().ApplyURI(
fmt.Sprintf("mongodb://%s:%v/", dbConfig.Host, dbConfig.Port),
)
if dbConfig.Username != "" {
clientOptions.SetAuth(options.Credential{
Username: dbConfig.Username,
Password: dbConfig.Password,
})
}
ctx, cancel := context.WithTimeout(ctx, 10*time.Second)
defer cancel()
client, err := mongo.Connect(ctx, clientOptions)
if err != nil {
return nil, err
}
// Check the connection
err = client.Ping(ctx, nil)
if err != nil {
return nil, err
}
return client, nil
}

View File

@ -0,0 +1,50 @@
package types
import "fmt"
type ConsumerCursor string
var (
ConsumerCursorLastConsumed ConsumerCursor = "last-consumed"
ConsumerCursorFirstStream ConsumerCursor = "first-stream"
ConsumerCursorCurrentStream ConsumerCursor = "current-stream"
)
func (c ConsumerCursor) String() string {
return string(c)
}
func (c ConsumerCursor) IsValid() bool {
return c == ConsumerCursorLastConsumed || c == ConsumerCursorFirstStream || c == ConsumerCursorCurrentStream
}
func (c ConsumerCursor) Equal(other ConsumerCursor) bool {
return c == other
}
func (c ConsumerCursor) IsLastConsumed() bool {
return c == ConsumerCursorLastConsumed
}
func (c ConsumerCursor) IsFirstStream() bool {
return c == ConsumerCursorFirstStream
}
func (c ConsumerCursor) IsCurrentStream() bool {
return c == ConsumerCursorCurrentStream
}
func (c *ConsumerCursor) Set(value string) error {
switch value {
case ConsumerCursorLastConsumed.String(), "":
*c = ConsumerCursorLastConsumed
case ConsumerCursorFirstStream.String():
*c = ConsumerCursorFirstStream
case ConsumerCursorCurrentStream.String():
*c = ConsumerCursorCurrentStream
default:
return fmt.Errorf("invalid cursor value: %s", value)
}
return nil
}

18
pkg/types/err_map.go Normal file
View File

@ -0,0 +1,18 @@
package types
type ErrMap map[string]error
func (ErrMap ErrMap) ToStringMap() map[string]string {
if len(ErrMap) == 0 {
return nil
}
stringMap := make(map[string]string)
for key, err := range ErrMap {
if err != nil {
stringMap[key] = err.Error()
}
}
return stringMap
}

7
pkg/types/errors.go Normal file
View File

@ -0,0 +1,7 @@
package types
import "errors"
var (
ErrInternal = errors.New("internal error")
)

View File

@ -0,0 +1,43 @@
package types
import "fmt"
type GeneratorCursor string
var (
GeneratorCursorLastGenerated GeneratorCursor = "last-generated"
GeneratorCursorFirstPost GeneratorCursor = "first-post"
)
func (c GeneratorCursor) String() string {
return string(c)
}
func (c GeneratorCursor) IsValid() bool {
return c == GeneratorCursorLastGenerated || c == GeneratorCursorFirstPost
}
func (c GeneratorCursor) Equal(other GeneratorCursor) bool {
return c == other
}
func (c GeneratorCursor) IsLastGenerated() bool {
return c == GeneratorCursorLastGenerated
}
func (c GeneratorCursor) IsFirstPost() bool {
return c == GeneratorCursorFirstPost
}
func (c *GeneratorCursor) Set(value string) error {
switch value {
case GeneratorCursorLastGenerated.String(), "":
*c = GeneratorCursorLastGenerated
case GeneratorCursorFirstPost.String():
*c = GeneratorCursorFirstPost
default:
return fmt.Errorf("invalid cursor value: %s", value)
}
return nil
}

151
pkg/utils/base.go Normal file
View File

@ -0,0 +1,151 @@
package utils
import (
"encoding/json"
"fmt"
"net/url"
"strconv"
"time"
"github.com/whyrusleeping/go-did"
)
// ParseString attempts to parse the input string `s` into a value of the specified type T.
// It supports parsing into the following types:
// - int, int8, int16, int32, int64
// - uint, uint8, uint16, uint32, uint64
// - float64
// - bool
// - string
// - time.Duration
// - url.URL / *url.URL
// - did.DID / *did.DID
//
// If T is not one of these supported types, it returns an error.
// If parsing the string `s` fails for a supported type, it returns the zero value of T
// and the parsing error.
func ParseString[T any](s string) (T, error) {
var value T
switch any(value).(type) {
case int:
i, err := strconv.Atoi(s)
if err != nil {
return value, err
}
value = any(i).(T)
case int8:
i, err := strconv.ParseInt(s, 10, 8)
if err != nil {
return value, err
}
value = any(int8(i)).(T)
case int16:
i, err := strconv.ParseInt(s, 10, 16)
if err != nil {
return value, err
}
value = any(int16(i)).(T)
case int32:
i, err := strconv.ParseInt(s, 10, 32)
if err != nil {
return value, err
}
value = any(int32(i)).(T)
case int64:
i, err := strconv.ParseInt(s, 10, 64)
if err != nil {
return value, err
}
value = any(i).(T)
case uint:
u, err := strconv.ParseUint(s, 10, 0)
if err != nil {
return value, err
}
value = any(uint(u)).(T)
case uint8:
u, err := strconv.ParseUint(s, 10, 8)
if err != nil {
return value, err
}
value = any(uint8(u)).(T)
case uint16:
u, err := strconv.ParseUint(s, 10, 16)
if err != nil {
return value, err
}
value = any(uint16(u)).(T)
case uint32:
u, err := strconv.ParseUint(s, 10, 32)
if err != nil {
return value, err
}
value = any(uint32(u)).(T)
case uint64:
u, err := strconv.ParseUint(s, 10, 64)
if err != nil {
return value, err
}
value = any(u).(T)
case float64:
f, err := strconv.ParseFloat(s, 64)
if err != nil {
return value, err
}
value = any(f).(T)
case bool:
b, err := strconv.ParseBool(s)
if err != nil {
return value, err
}
value = any(b).(T)
case string:
value = any(s).(T)
case []string:
var items []string
err := json.Unmarshal([]byte(s), &items)
if err != nil {
return value, err
}
value = any(items).(T)
case time.Duration:
d, err := time.ParseDuration(s)
if err != nil {
return value, err
}
value = any(d).(T)
case url.URL:
u, err := url.Parse(s)
if err != nil {
return value, err
}
value = any(*u).(T)
case *url.URL:
u, err := url.Parse(s)
if err != nil {
return value, err
}
value = any(u).(T)
case did.DID:
d, err := did.ParseDID(s)
if err != nil {
return value, err
}
value = any(d).(T)
case *did.DID:
d, err := did.ParseDID(s)
if err != nil {
return value, err
}
value = any(&d).(T)
default:
return value, fmt.Errorf("unsupported type: %T", value)
}
return value, nil
}
func ToPtr[T any](value T) *T {
return &value
}

50
pkg/utils/env.go Normal file
View File

@ -0,0 +1,50 @@
package utils
import (
"fmt"
"os"
)
// GetEnv retrieves the environment variable named by the key envName,
// and attempts to parse its value into the specified type T.
//
// It returns the parsed value of type T and a nil error on success.
// It returns a zero value of type T and an error if the environment
// variable is not set, or if parsing fails using the ParseValue function.
func GetEnv[T any](envName string) (T, error) {
var zero T
envStr := os.Getenv(envName)
if envStr == "" {
return zero, fmt.Errorf("environment variable %s is not set", envName)
}
parsedEnv, err := ParseString[T](envStr)
if err != nil {
return zero, fmt.Errorf("failed to parse environment variable %s: %s", envName, err)
}
return parsedEnv, nil
}
// GetEnvOr retrieves the environment variable named by the key envName,
// and attempts to parse its value into the specified type T.
//
// It returns the parsed value of type T and a nil error on success.
// If the environment variable is not set, it returns the provided default value
// and a nil error. If parsing fails, it returns a zero value of type T and an error.
func GetEnvOr[T any](envName string, defaultValue T) (T, error) {
var zero T
envStr := os.Getenv(envName)
if envStr == "" {
return defaultValue, nil
}
parsedEnv, err := ParseString[T](envStr)
if err != nil {
return zero, fmt.Errorf("failed to parse environment variable %s: %s", envName, err)
}
return parsedEnv, nil
}