Add files via upload
This commit is contained in:
commit
f2739423b0
9
.dockerignore
Normal file
9
.dockerignore
Normal file
@ -0,0 +1,9 @@
|
|||||||
|
node_modules
|
||||||
|
npm-debug.log
|
||||||
|
dist
|
||||||
|
.git
|
||||||
|
.github
|
||||||
|
.vscode
|
||||||
|
coverage
|
||||||
|
.env
|
||||||
|
*.md
|
22
.env.example
Normal file
22
.env.example
Normal file
@ -0,0 +1,22 @@
|
|||||||
|
NICKNAME=example
|
||||||
|
FINGERPRINT=A8989865AHI456JNGER897RGEGR
|
||||||
|
NODE_ENV=development
|
||||||
|
PORT=7777
|
||||||
|
ENABLE_ANYONE=false
|
||||||
|
HOSTNAME=127.0.0.1
|
||||||
|
ADMIN_WALLET=0954689080954860945
|
||||||
|
ENABLE_LOAD_BALANCING=true
|
||||||
|
SERVICE_DISCOVERY_TOPIC=debros-service-discovery
|
||||||
|
HEARTBEAT_INTERVAL=5000
|
||||||
|
STALE_PEER_TIMEOUT=30000
|
||||||
|
PEER_LOG_INTERVAL=60000
|
||||||
|
NODE_PUBLIC_ADDRESS=127.0.0.1
|
||||||
|
BOOTSTRAP_NODES=
|
||||||
|
MAX_CONNECTIONS=1000
|
||||||
|
LOAD_BALANCING_STRATEGY=least-loaded
|
||||||
|
ACCEPT_TERMS=true
|
||||||
|
KEY_PATH=/var/lib/debros/keys
|
||||||
|
LIBP2P_DEBUG=true
|
||||||
|
IPFS_DEBUG=true
|
||||||
|
LOG_LEVEL=debug
|
||||||
|
DEBUG=libp2p:*
|
12
.gitignore
vendored
Normal file
12
.gitignore
vendored
Normal file
@ -0,0 +1,12 @@
|
|||||||
|
node_modules/
|
||||||
|
.env
|
||||||
|
radata/
|
||||||
|
dist/
|
||||||
|
blockstore/
|
||||||
|
orbitdb/
|
||||||
|
swarm.key
|
||||||
|
.DS_Store
|
||||||
|
bin/
|
||||||
|
blockstore-*
|
||||||
|
logs/
|
||||||
|
packages/
|
8
.prettierrc
Normal file
8
.prettierrc
Normal file
@ -0,0 +1,8 @@
|
|||||||
|
{
|
||||||
|
"printWidth": 120,
|
||||||
|
"trailingComma": "es5",
|
||||||
|
"tabWidth": 2,
|
||||||
|
"useTabs": false,
|
||||||
|
"semi": true,
|
||||||
|
"singleQuote": true
|
||||||
|
}
|
24
Dockerfile
Normal file
24
Dockerfile
Normal file
@ -0,0 +1,24 @@
|
|||||||
|
FROM node:20-alpine
|
||||||
|
|
||||||
|
WORKDIR /app
|
||||||
|
|
||||||
|
# Install pnpm
|
||||||
|
RUN npm install -g pnpm@10.6.2
|
||||||
|
|
||||||
|
# Copy package files first to leverage Docker caching
|
||||||
|
COPY package.json pnpm-lock.yaml ./
|
||||||
|
|
||||||
|
# Install dependencies
|
||||||
|
RUN pnpm install
|
||||||
|
|
||||||
|
# Copy the rest of the project files
|
||||||
|
COPY . .
|
||||||
|
|
||||||
|
# Build the TypeScript project
|
||||||
|
RUN pnpm build
|
||||||
|
|
||||||
|
# Expose port
|
||||||
|
EXPOSE 7777
|
||||||
|
|
||||||
|
# Run the application
|
||||||
|
CMD ["pnpm", "start"]
|
21
Dockerfile.dev
Normal file
21
Dockerfile.dev
Normal file
@ -0,0 +1,21 @@
|
|||||||
|
FROM node:20-alpine
|
||||||
|
|
||||||
|
WORKDIR /app
|
||||||
|
|
||||||
|
# Install dependencies
|
||||||
|
COPY package*.json ./
|
||||||
|
|
||||||
|
RUN npm install
|
||||||
|
|
||||||
|
# Install tsx
|
||||||
|
RUN npm install -g tsx
|
||||||
|
|
||||||
|
# Copy source code
|
||||||
|
COPY src/ ./
|
||||||
|
COPY tsconfig.json ./
|
||||||
|
|
||||||
|
# Expose port
|
||||||
|
EXPOSE 7777
|
||||||
|
|
||||||
|
# Run the TypeScript file directly
|
||||||
|
CMD ["tsx", "watch", "server.ts"]
|
595
LICENSE
Normal file
595
LICENSE
Normal file
@ -0,0 +1,595 @@
|
|||||||
|
GNU General Public License
|
||||||
|
==========================
|
||||||
|
|
||||||
|
_Version 3, 29 June 2007_
|
||||||
|
_Copyright © 2007 Free Software Foundation, Inc. <<http://fsf.org/>>_
|
||||||
|
|
||||||
|
Everyone is permitted to copy and distribute verbatim copies of this license
|
||||||
|
document, but changing it is not allowed.
|
||||||
|
|
||||||
|
## Preamble
|
||||||
|
|
||||||
|
The GNU General Public License is a free, copyleft license for software and other
|
||||||
|
kinds of works.
|
||||||
|
|
||||||
|
The licenses for most software and other practical works are designed to take away
|
||||||
|
your freedom to share and change the works. By contrast, the GNU General Public
|
||||||
|
License is intended to guarantee your freedom to share and change all versions of a
|
||||||
|
program--to make sure it remains free software for all its users. We, the Free
|
||||||
|
Software Foundation, use the GNU General Public License for most of our software; it
|
||||||
|
applies also to any other work released this way by its authors. You can apply it to
|
||||||
|
your programs, too.
|
||||||
|
|
||||||
|
When we speak of free software, we are referring to freedom, not price. Our General
|
||||||
|
Public Licenses are designed to make sure that you have the freedom to distribute
|
||||||
|
copies of free software (and charge for them if you wish), that you receive source
|
||||||
|
code or can get it if you want it, that you can change the software or use pieces of
|
||||||
|
it in new free programs, and that you know you can do these things.
|
||||||
|
|
||||||
|
To protect your rights, we need to prevent others from denying you these rights or
|
||||||
|
asking you to surrender the rights. Therefore, you have certain responsibilities if
|
||||||
|
you distribute copies of the software, or if you modify it: responsibilities to
|
||||||
|
respect the freedom of others.
|
||||||
|
|
||||||
|
For example, if you distribute copies of such a program, whether gratis or for a fee,
|
||||||
|
you must pass on to the recipients the same freedoms that you received. You must make
|
||||||
|
sure that they, too, receive or can get the source code. And you must show them these
|
||||||
|
terms so they know their rights.
|
||||||
|
|
||||||
|
Developers that use the GNU GPL protect your rights with two steps: **(1)** assert
|
||||||
|
copyright on the software, and **(2)** offer you this License giving you legal permission
|
||||||
|
to copy, distribute and/or modify it.
|
||||||
|
|
||||||
|
For the developers' and authors' protection, the GPL clearly explains that there is
|
||||||
|
no warranty for this free software. For both users' and authors' sake, the GPL
|
||||||
|
requires that modified versions be marked as changed, so that their problems will not
|
||||||
|
be attributed erroneously to authors of previous versions.
|
||||||
|
|
||||||
|
Some devices are designed to deny users access to install or run modified versions of
|
||||||
|
the software inside them, although the manufacturer can do so. This is fundamentally
|
||||||
|
incompatible with the aim of protecting users' freedom to change the software. The
|
||||||
|
systematic pattern of such abuse occurs in the area of products for individuals to
|
||||||
|
use, which is precisely where it is most unacceptable. Therefore, we have designed
|
||||||
|
this version of the GPL to prohibit the practice for those products. If such problems
|
||||||
|
arise substantially in other domains, we stand ready to extend this provision to
|
||||||
|
those domains in future versions of the GPL, as needed to protect the freedom of
|
||||||
|
users.
|
||||||
|
|
||||||
|
Finally, every program is threatened constantly by software patents. States should
|
||||||
|
not allow patents to restrict development and use of software on general-purpose
|
||||||
|
computers, but in those that do, we wish to avoid the special danger that patents
|
||||||
|
applied to a free program could make it effectively proprietary. To prevent this, the
|
||||||
|
GPL assures that patents cannot be used to render the program non-free.
|
||||||
|
|
||||||
|
The precise terms and conditions for copying, distribution and modification follow.
|
||||||
|
|
||||||
|
## TERMS AND CONDITIONS
|
||||||
|
|
||||||
|
### 0. Definitions
|
||||||
|
|
||||||
|
“This License” refers to version 3 of the GNU General Public License.
|
||||||
|
|
||||||
|
“Copyright” also means copyright-like laws that apply to other kinds of
|
||||||
|
works, such as semiconductor masks.
|
||||||
|
|
||||||
|
“The Program” refers to any copyrightable work licensed under this
|
||||||
|
License. Each licensee is addressed as “you”. “Licensees” and
|
||||||
|
“recipients” may be individuals or organizations.
|
||||||
|
|
||||||
|
To “modify” a work means to copy from or adapt all or part of the work in
|
||||||
|
a fashion requiring copyright permission, other than the making of an exact copy. The
|
||||||
|
resulting work is called a “modified version” of the earlier work or a
|
||||||
|
work “based on” the earlier work.
|
||||||
|
|
||||||
|
A “covered work” means either the unmodified Program or a work based on
|
||||||
|
the Program.
|
||||||
|
|
||||||
|
To “propagate” a work means to do anything with it that, without
|
||||||
|
permission, would make you directly or secondarily liable for infringement under
|
||||||
|
applicable copyright law, except executing it on a computer or modifying a private
|
||||||
|
copy. Propagation includes copying, distribution (with or without modification),
|
||||||
|
making available to the public, and in some countries other activities as well.
|
||||||
|
|
||||||
|
To “convey” a work means any kind of propagation that enables other
|
||||||
|
parties to make or receive copies. Mere interaction with a user through a computer
|
||||||
|
network, with no transfer of a copy, is not conveying.
|
||||||
|
|
||||||
|
An interactive user interface displays “Appropriate Legal Notices” to the
|
||||||
|
extent that it includes a convenient and prominently visible feature that **(1)**
|
||||||
|
displays an appropriate copyright notice, and **(2)** tells the user that there is no
|
||||||
|
warranty for the work (except to the extent that warranties are provided), that
|
||||||
|
licensees may convey the work under this License, and how to view a copy of this
|
||||||
|
License. If the interface presents a list of user commands or options, such as a
|
||||||
|
menu, a prominent item in the list meets this criterion.
|
||||||
|
|
||||||
|
### 1. Source Code
|
||||||
|
|
||||||
|
The “source code” for a work means the preferred form of the work for
|
||||||
|
making modifications to it. “Object code” means any non-source form of a
|
||||||
|
work.
|
||||||
|
|
||||||
|
A “Standard Interface” means an interface that either is an official
|
||||||
|
standard defined by a recognized standards body, or, in the case of interfaces
|
||||||
|
specified for a particular programming language, one that is widely used among
|
||||||
|
developers working in that language.
|
||||||
|
|
||||||
|
The “System Libraries” of an executable work include anything, other than
|
||||||
|
the work as a whole, that **(a)** is included in the normal form of packaging a Major
|
||||||
|
Component, but which is not part of that Major Component, and **(b)** serves only to
|
||||||
|
enable use of the work with that Major Component, or to implement a Standard
|
||||||
|
Interface for which an implementation is available to the public in source code form.
|
||||||
|
A “Major Component”, in this context, means a major essential component
|
||||||
|
(kernel, window system, and so on) of the specific operating system (if any) on which
|
||||||
|
the executable work runs, or a compiler used to produce the work, or an object code
|
||||||
|
interpreter used to run it.
|
||||||
|
|
||||||
|
The “Corresponding Source” for a work in object code form means all the
|
||||||
|
source code needed to generate, install, and (for an executable work) run the object
|
||||||
|
code and to modify the work, including scripts to control those activities. However,
|
||||||
|
it does not include the work's System Libraries, or general-purpose tools or
|
||||||
|
generally available free programs which are used unmodified in performing those
|
||||||
|
activities but which are not part of the work. For example, Corresponding Source
|
||||||
|
includes interface definition files associated with source files for the work, and
|
||||||
|
the source code for shared libraries and dynamically linked subprograms that the work
|
||||||
|
is specifically designed to require, such as by intimate data communication or
|
||||||
|
control flow between those subprograms and other parts of the work.
|
||||||
|
|
||||||
|
The Corresponding Source need not include anything that users can regenerate
|
||||||
|
automatically from other parts of the Corresponding Source.
|
||||||
|
|
||||||
|
The Corresponding Source for a work in source code form is that same work.
|
||||||
|
|
||||||
|
### 2. Basic Permissions
|
||||||
|
|
||||||
|
All rights granted under this License are granted for the term of copyright on the
|
||||||
|
Program, and are irrevocable provided the stated conditions are met. This License
|
||||||
|
explicitly affirms your unlimited permission to run the unmodified Program. The
|
||||||
|
output from running a covered work is covered by this License only if the output,
|
||||||
|
given its content, constitutes a covered work. This License acknowledges your rights
|
||||||
|
of fair use or other equivalent, as provided by copyright law.
|
||||||
|
|
||||||
|
You may make, run and propagate covered works that you do not convey, without
|
||||||
|
conditions so long as your license otherwise remains in force. You may convey covered
|
||||||
|
works to others for the sole purpose of having them make modifications exclusively
|
||||||
|
for you, or provide you with facilities for running those works, provided that you
|
||||||
|
comply with the terms of this License in conveying all material for which you do not
|
||||||
|
control copyright. Those thus making or running the covered works for you must do so
|
||||||
|
exclusively on your behalf, under your direction and control, on terms that prohibit
|
||||||
|
them from making any copies of your copyrighted material outside their relationship
|
||||||
|
with you.
|
||||||
|
|
||||||
|
Conveying under any other circumstances is permitted solely under the conditions
|
||||||
|
stated below. Sublicensing is not allowed; section 10 makes it unnecessary.
|
||||||
|
|
||||||
|
### 3. Protecting Users' Legal Rights From Anti-Circumvention Law
|
||||||
|
|
||||||
|
No covered work shall be deemed part of an effective technological measure under any
|
||||||
|
applicable law fulfilling obligations under article 11 of the WIPO copyright treaty
|
||||||
|
adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention
|
||||||
|
of such measures.
|
||||||
|
|
||||||
|
When you convey a covered work, you waive any legal power to forbid circumvention of
|
||||||
|
technological measures to the extent such circumvention is effected by exercising
|
||||||
|
rights under this License with respect to the covered work, and you disclaim any
|
||||||
|
intention to limit operation or modification of the work as a means of enforcing,
|
||||||
|
against the work's users, your or third parties' legal rights to forbid circumvention
|
||||||
|
of technological measures.
|
||||||
|
|
||||||
|
### 4. Conveying Verbatim Copies
|
||||||
|
|
||||||
|
You may convey verbatim copies of the Program's source code as you receive it, in any
|
||||||
|
medium, provided that you conspicuously and appropriately publish on each copy an
|
||||||
|
appropriate copyright notice; keep intact all notices stating that this License and
|
||||||
|
any non-permissive terms added in accord with section 7 apply to the code; keep
|
||||||
|
intact all notices of the absence of any warranty; and give all recipients a copy of
|
||||||
|
this License along with the Program.
|
||||||
|
|
||||||
|
You may charge any price or no price for each copy that you convey, and you may offer
|
||||||
|
support or warranty protection for a fee.
|
||||||
|
|
||||||
|
### 5. Conveying Modified Source Versions
|
||||||
|
|
||||||
|
You may convey a work based on the Program, or the modifications to produce it from
|
||||||
|
the Program, in the form of source code under the terms of section 4, provided that
|
||||||
|
you also meet all of these conditions:
|
||||||
|
|
||||||
|
* **a)** The work must carry prominent notices stating that you modified it, and giving a
|
||||||
|
relevant date.
|
||||||
|
* **b)** The work must carry prominent notices stating that it is released under this
|
||||||
|
License and any conditions added under section 7. This requirement modifies the
|
||||||
|
requirement in section 4 to “keep intact all notices”.
|
||||||
|
* **c)** You must license the entire work, as a whole, under this License to anyone who
|
||||||
|
comes into possession of a copy. This License will therefore apply, along with any
|
||||||
|
applicable section 7 additional terms, to the whole of the work, and all its parts,
|
||||||
|
regardless of how they are packaged. This License gives no permission to license the
|
||||||
|
work in any other way, but it does not invalidate such permission if you have
|
||||||
|
separately received it.
|
||||||
|
* **d)** If the work has interactive user interfaces, each must display Appropriate Legal
|
||||||
|
Notices; however, if the Program has interactive interfaces that do not display
|
||||||
|
Appropriate Legal Notices, your work need not make them do so.
|
||||||
|
|
||||||
|
A compilation of a covered work with other separate and independent works, which are
|
||||||
|
not by their nature extensions of the covered work, and which are not combined with
|
||||||
|
it such as to form a larger program, in or on a volume of a storage or distribution
|
||||||
|
medium, is called an “aggregate” if the compilation and its resulting
|
||||||
|
copyright are not used to limit the access or legal rights of the compilation's users
|
||||||
|
beyond what the individual works permit. Inclusion of a covered work in an aggregate
|
||||||
|
does not cause this License to apply to the other parts of the aggregate.
|
||||||
|
|
||||||
|
### 6. Conveying Non-Source Forms
|
||||||
|
|
||||||
|
You may convey a covered work in object code form under the terms of sections 4 and
|
||||||
|
5, provided that you also convey the machine-readable Corresponding Source under the
|
||||||
|
terms of this License, in one of these ways:
|
||||||
|
|
||||||
|
* **a)** Convey the object code in, or embodied in, a physical product (including a
|
||||||
|
physical distribution medium), accompanied by the Corresponding Source fixed on a
|
||||||
|
durable physical medium customarily used for software interchange.
|
||||||
|
* **b)** Convey the object code in, or embodied in, a physical product (including a
|
||||||
|
physical distribution medium), accompanied by a written offer, valid for at least
|
||||||
|
three years and valid for as long as you offer spare parts or customer support for
|
||||||
|
that product model, to give anyone who possesses the object code either **(1)** a copy of
|
||||||
|
the Corresponding Source for all the software in the product that is covered by this
|
||||||
|
License, on a durable physical medium customarily used for software interchange, for
|
||||||
|
a price no more than your reasonable cost of physically performing this conveying of
|
||||||
|
source, or **(2)** access to copy the Corresponding Source from a network server at no
|
||||||
|
charge.
|
||||||
|
* **c)** Convey individual copies of the object code with a copy of the written offer to
|
||||||
|
provide the Corresponding Source. This alternative is allowed only occasionally and
|
||||||
|
noncommercially, and only if you received the object code with such an offer, in
|
||||||
|
accord with subsection 6b.
|
||||||
|
* **d)** Convey the object code by offering access from a designated place (gratis or for
|
||||||
|
a charge), and offer equivalent access to the Corresponding Source in the same way
|
||||||
|
through the same place at no further charge. You need not require recipients to copy
|
||||||
|
the Corresponding Source along with the object code. If the place to copy the object
|
||||||
|
code is a network server, the Corresponding Source may be on a different server
|
||||||
|
(operated by you or a third party) that supports equivalent copying facilities,
|
||||||
|
provided you maintain clear directions next to the object code saying where to find
|
||||||
|
the Corresponding Source. Regardless of what server hosts the Corresponding Source,
|
||||||
|
you remain obligated to ensure that it is available for as long as needed to satisfy
|
||||||
|
these requirements.
|
||||||
|
* **e)** Convey the object code using peer-to-peer transmission, provided you inform
|
||||||
|
other peers where the object code and Corresponding Source of the work are being
|
||||||
|
offered to the general public at no charge under subsection 6d.
|
||||||
|
|
||||||
|
A separable portion of the object code, whose source code is excluded from the
|
||||||
|
Corresponding Source as a System Library, need not be included in conveying the
|
||||||
|
object code work.
|
||||||
|
|
||||||
|
A “User Product” is either **(1)** a “consumer product”, which
|
||||||
|
means any tangible personal property which is normally used for personal, family, or
|
||||||
|
household purposes, or **(2)** anything designed or sold for incorporation into a
|
||||||
|
dwelling. In determining whether a product is a consumer product, doubtful cases
|
||||||
|
shall be resolved in favor of coverage. For a particular product received by a
|
||||||
|
particular user, “normally used” refers to a typical or common use of
|
||||||
|
that class of product, regardless of the status of the particular user or of the way
|
||||||
|
in which the particular user actually uses, or expects or is expected to use, the
|
||||||
|
product. A product is a consumer product regardless of whether the product has
|
||||||
|
substantial commercial, industrial or non-consumer uses, unless such uses represent
|
||||||
|
the only significant mode of use of the product.
|
||||||
|
|
||||||
|
“Installation Information” for a User Product means any methods,
|
||||||
|
procedures, authorization keys, or other information required to install and execute
|
||||||
|
modified versions of a covered work in that User Product from a modified version of
|
||||||
|
its Corresponding Source. The information must suffice to ensure that the continued
|
||||||
|
functioning of the modified object code is in no case prevented or interfered with
|
||||||
|
solely because modification has been made.
|
||||||
|
|
||||||
|
If you convey an object code work under this section in, or with, or specifically for
|
||||||
|
use in, a User Product, and the conveying occurs as part of a transaction in which
|
||||||
|
the right of possession and use of the User Product is transferred to the recipient
|
||||||
|
in perpetuity or for a fixed term (regardless of how the transaction is
|
||||||
|
characterized), the Corresponding Source conveyed under this section must be
|
||||||
|
accompanied by the Installation Information. But this requirement does not apply if
|
||||||
|
neither you nor any third party retains the ability to install modified object code
|
||||||
|
on the User Product (for example, the work has been installed in ROM).
|
||||||
|
|
||||||
|
The requirement to provide Installation Information does not include a requirement to
|
||||||
|
continue to provide support service, warranty, or updates for a work that has been
|
||||||
|
modified or installed by the recipient, or for the User Product in which it has been
|
||||||
|
modified or installed. Access to a network may be denied when the modification itself
|
||||||
|
materially and adversely affects the operation of the network or violates the rules
|
||||||
|
and protocols for communication across the network.
|
||||||
|
|
||||||
|
Corresponding Source conveyed, and Installation Information provided, in accord with
|
||||||
|
this section must be in a format that is publicly documented (and with an
|
||||||
|
implementation available to the public in source code form), and must require no
|
||||||
|
special password or key for unpacking, reading or copying.
|
||||||
|
|
||||||
|
### 7. Additional Terms
|
||||||
|
|
||||||
|
“Additional permissions” are terms that supplement the terms of this
|
||||||
|
License by making exceptions from one or more of its conditions. Additional
|
||||||
|
permissions that are applicable to the entire Program shall be treated as though they
|
||||||
|
were included in this License, to the extent that they are valid under applicable
|
||||||
|
law. If additional permissions apply only to part of the Program, that part may be
|
||||||
|
used separately under those permissions, but the entire Program remains governed by
|
||||||
|
this License without regard to the additional permissions.
|
||||||
|
|
||||||
|
When you convey a copy of a covered work, you may at your option remove any
|
||||||
|
additional permissions from that copy, or from any part of it. (Additional
|
||||||
|
permissions may be written to require their own removal in certain cases when you
|
||||||
|
modify the work.) You may place additional permissions on material, added by you to a
|
||||||
|
covered work, for which you have or can give appropriate copyright permission.
|
||||||
|
|
||||||
|
Notwithstanding any other provision of this License, for material you add to a
|
||||||
|
covered work, you may (if authorized by the copyright holders of that material)
|
||||||
|
supplement the terms of this License with terms:
|
||||||
|
|
||||||
|
* **a)** Disclaiming warranty or limiting liability differently from the terms of
|
||||||
|
sections 15 and 16 of this License; or
|
||||||
|
* **b)** Requiring preservation of specified reasonable legal notices or author
|
||||||
|
attributions in that material or in the Appropriate Legal Notices displayed by works
|
||||||
|
containing it; or
|
||||||
|
* **c)** Prohibiting misrepresentation of the origin of that material, or requiring that
|
||||||
|
modified versions of such material be marked in reasonable ways as different from the
|
||||||
|
original version; or
|
||||||
|
* **d)** Limiting the use for publicity purposes of names of licensors or authors of the
|
||||||
|
material; or
|
||||||
|
* **e)** Declining to grant rights under trademark law for use of some trade names,
|
||||||
|
trademarks, or service marks; or
|
||||||
|
* **f)** Requiring indemnification of licensors and authors of that material by anyone
|
||||||
|
who conveys the material (or modified versions of it) with contractual assumptions of
|
||||||
|
liability to the recipient, for any liability that these contractual assumptions
|
||||||
|
directly impose on those licensors and authors.
|
||||||
|
|
||||||
|
All other non-permissive additional terms are considered “further
|
||||||
|
restrictions” within the meaning of section 10. If the Program as you received
|
||||||
|
it, or any part of it, contains a notice stating that it is governed by this License
|
||||||
|
along with a term that is a further restriction, you may remove that term. If a
|
||||||
|
license document contains a further restriction but permits relicensing or conveying
|
||||||
|
under this License, you may add to a covered work material governed by the terms of
|
||||||
|
that license document, provided that the further restriction does not survive such
|
||||||
|
relicensing or conveying.
|
||||||
|
|
||||||
|
If you add terms to a covered work in accord with this section, you must place, in
|
||||||
|
the relevant source files, a statement of the additional terms that apply to those
|
||||||
|
files, or a notice indicating where to find the applicable terms.
|
||||||
|
|
||||||
|
Additional terms, permissive or non-permissive, may be stated in the form of a
|
||||||
|
separately written license, or stated as exceptions; the above requirements apply
|
||||||
|
either way.
|
||||||
|
|
||||||
|
### 8. Termination
|
||||||
|
|
||||||
|
You may not propagate or modify a covered work except as expressly provided under
|
||||||
|
this License. Any attempt otherwise to propagate or modify it is void, and will
|
||||||
|
automatically terminate your rights under this License (including any patent licenses
|
||||||
|
granted under the third paragraph of section 11).
|
||||||
|
|
||||||
|
However, if you cease all violation of this License, then your license from a
|
||||||
|
particular copyright holder is reinstated **(a)** provisionally, unless and until the
|
||||||
|
copyright holder explicitly and finally terminates your license, and **(b)** permanently,
|
||||||
|
if the copyright holder fails to notify you of the violation by some reasonable means
|
||||||
|
prior to 60 days after the cessation.
|
||||||
|
|
||||||
|
Moreover, your license from a particular copyright holder is reinstated permanently
|
||||||
|
if the copyright holder notifies you of the violation by some reasonable means, this
|
||||||
|
is the first time you have received notice of violation of this License (for any
|
||||||
|
work) from that copyright holder, and you cure the violation prior to 30 days after
|
||||||
|
your receipt of the notice.
|
||||||
|
|
||||||
|
Termination of your rights under this section does not terminate the licenses of
|
||||||
|
parties who have received copies or rights from you under this License. If your
|
||||||
|
rights have been terminated and not permanently reinstated, you do not qualify to
|
||||||
|
receive new licenses for the same material under section 10.
|
||||||
|
|
||||||
|
### 9. Acceptance Not Required for Having Copies
|
||||||
|
|
||||||
|
You are not required to accept this License in order to receive or run a copy of the
|
||||||
|
Program. Ancillary propagation of a covered work occurring solely as a consequence of
|
||||||
|
using peer-to-peer transmission to receive a copy likewise does not require
|
||||||
|
acceptance. However, nothing other than this License grants you permission to
|
||||||
|
propagate or modify any covered work. These actions infringe copyright if you do not
|
||||||
|
accept this License. Therefore, by modifying or propagating a covered work, you
|
||||||
|
indicate your acceptance of this License to do so.
|
||||||
|
|
||||||
|
### 10. Automatic Licensing of Downstream Recipients
|
||||||
|
|
||||||
|
Each time you convey a covered work, the recipient automatically receives a license
|
||||||
|
from the original licensors, to run, modify and propagate that work, subject to this
|
||||||
|
License. You are not responsible for enforcing compliance by third parties with this
|
||||||
|
License.
|
||||||
|
|
||||||
|
An “entity transaction” is a transaction transferring control of an
|
||||||
|
organization, or substantially all assets of one, or subdividing an organization, or
|
||||||
|
merging organizations. If propagation of a covered work results from an entity
|
||||||
|
transaction, each party to that transaction who receives a copy of the work also
|
||||||
|
receives whatever licenses to the work the party's predecessor in interest had or
|
||||||
|
could give under the previous paragraph, plus a right to possession of the
|
||||||
|
Corresponding Source of the work from the predecessor in interest, if the predecessor
|
||||||
|
has it or can get it with reasonable efforts.
|
||||||
|
|
||||||
|
You may not impose any further restrictions on the exercise of the rights granted or
|
||||||
|
affirmed under this License. For example, you may not impose a license fee, royalty,
|
||||||
|
or other charge for exercise of rights granted under this License, and you may not
|
||||||
|
initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging
|
||||||
|
that any patent claim is infringed by making, using, selling, offering for sale, or
|
||||||
|
importing the Program or any portion of it.
|
||||||
|
|
||||||
|
### 11. Patents
|
||||||
|
|
||||||
|
A “contributor” is a copyright holder who authorizes use under this
|
||||||
|
License of the Program or a work on which the Program is based. The work thus
|
||||||
|
licensed is called the contributor's “contributor version”.
|
||||||
|
|
||||||
|
A contributor's “essential patent claims” are all patent claims owned or
|
||||||
|
controlled by the contributor, whether already acquired or hereafter acquired, that
|
||||||
|
would be infringed by some manner, permitted by this License, of making, using, or
|
||||||
|
selling its contributor version, but do not include claims that would be infringed
|
||||||
|
only as a consequence of further modification of the contributor version. For
|
||||||
|
purposes of this definition, “control” includes the right to grant patent
|
||||||
|
sublicenses in a manner consistent with the requirements of this License.
|
||||||
|
|
||||||
|
Each contributor grants you a non-exclusive, worldwide, royalty-free patent license
|
||||||
|
under the contributor's essential patent claims, to make, use, sell, offer for sale,
|
||||||
|
import and otherwise run, modify and propagate the contents of its contributor
|
||||||
|
version.
|
||||||
|
|
||||||
|
In the following three paragraphs, a “patent license” is any express
|
||||||
|
agreement or commitment, however denominated, not to enforce a patent (such as an
|
||||||
|
express permission to practice a patent or covenant not to sue for patent
|
||||||
|
infringement). To “grant” such a patent license to a party means to make
|
||||||
|
such an agreement or commitment not to enforce a patent against the party.
|
||||||
|
|
||||||
|
If you convey a covered work, knowingly relying on a patent license, and the
|
||||||
|
Corresponding Source of the work is not available for anyone to copy, free of charge
|
||||||
|
and under the terms of this License, through a publicly available network server or
|
||||||
|
other readily accessible means, then you must either **(1)** cause the Corresponding
|
||||||
|
Source to be so available, or **(2)** arrange to deprive yourself of the benefit of the
|
||||||
|
patent license for this particular work, or **(3)** arrange, in a manner consistent with
|
||||||
|
the requirements of this License, to extend the patent license to downstream
|
||||||
|
recipients. “Knowingly relying” means you have actual knowledge that, but
|
||||||
|
for the patent license, your conveying the covered work in a country, or your
|
||||||
|
recipient's use of the covered work in a country, would infringe one or more
|
||||||
|
identifiable patents in that country that you have reason to believe are valid.
|
||||||
|
|
||||||
|
If, pursuant to or in connection with a single transaction or arrangement, you
|
||||||
|
convey, or propagate by procuring conveyance of, a covered work, and grant a patent
|
||||||
|
license to some of the parties receiving the covered work authorizing them to use,
|
||||||
|
propagate, modify or convey a specific copy of the covered work, then the patent
|
||||||
|
license you grant is automatically extended to all recipients of the covered work and
|
||||||
|
works based on it.
|
||||||
|
|
||||||
|
A patent license is “discriminatory” if it does not include within the
|
||||||
|
scope of its coverage, prohibits the exercise of, or is conditioned on the
|
||||||
|
non-exercise of one or more of the rights that are specifically granted under this
|
||||||
|
License. You may not convey a covered work if you are a party to an arrangement with
|
||||||
|
a third party that is in the business of distributing software, under which you make
|
||||||
|
payment to the third party based on the extent of your activity of conveying the
|
||||||
|
work, and under which the third party grants, to any of the parties who would receive
|
||||||
|
the covered work from you, a discriminatory patent license **(a)** in connection with
|
||||||
|
copies of the covered work conveyed by you (or copies made from those copies), or **(b)**
|
||||||
|
primarily for and in connection with specific products or compilations that contain
|
||||||
|
the covered work, unless you entered into that arrangement, or that patent license
|
||||||
|
was granted, prior to 28 March 2007.
|
||||||
|
|
||||||
|
Nothing in this License shall be construed as excluding or limiting any implied
|
||||||
|
license or other defenses to infringement that may otherwise be available to you
|
||||||
|
under applicable patent law.
|
||||||
|
|
||||||
|
### 12. No Surrender of Others' Freedom
|
||||||
|
|
||||||
|
If conditions are imposed on you (whether by court order, agreement or otherwise)
|
||||||
|
that contradict the conditions of this License, they do not excuse you from the
|
||||||
|
conditions of this License. If you cannot convey a covered work so as to satisfy
|
||||||
|
simultaneously your obligations under this License and any other pertinent
|
||||||
|
obligations, then as a consequence you may not convey it at all. For example, if you
|
||||||
|
agree to terms that obligate you to collect a royalty for further conveying from
|
||||||
|
those to whom you convey the Program, the only way you could satisfy both those terms
|
||||||
|
and this License would be to refrain entirely from conveying the Program.
|
||||||
|
|
||||||
|
### 13. Use with the GNU Affero General Public License
|
||||||
|
|
||||||
|
Notwithstanding any other provision of this License, you have permission to link or
|
||||||
|
combine any covered work with a work licensed under version 3 of the GNU Affero
|
||||||
|
General Public License into a single combined work, and to convey the resulting work.
|
||||||
|
The terms of this License will continue to apply to the part which is the covered
|
||||||
|
work, but the special requirements of the GNU Affero General Public License, section
|
||||||
|
13, concerning interaction through a network will apply to the combination as such.
|
||||||
|
|
||||||
|
### 14. Revised Versions of this License
|
||||||
|
|
||||||
|
The Free Software Foundation may publish revised and/or new versions of the GNU
|
||||||
|
General Public License from time to time. Such new versions will be similar in spirit
|
||||||
|
to the present version, but may differ in detail to address new problems or concerns.
|
||||||
|
|
||||||
|
Each version is given a distinguishing version number. If the Program specifies that
|
||||||
|
a certain numbered version of the GNU General Public License “or any later
|
||||||
|
version” applies to it, you have the option of following the terms and
|
||||||
|
conditions either of that numbered version or of any later version published by the
|
||||||
|
Free Software Foundation. If the Program does not specify a version number of the GNU
|
||||||
|
General Public License, you may choose any version ever published by the Free
|
||||||
|
Software Foundation.
|
||||||
|
|
||||||
|
If the Program specifies that a proxy can decide which future versions of the GNU
|
||||||
|
General Public License can be used, that proxy's public statement of acceptance of a
|
||||||
|
version permanently authorizes you to choose that version for the Program.
|
||||||
|
|
||||||
|
Later license versions may give you additional or different permissions. However, no
|
||||||
|
additional obligations are imposed on any author or copyright holder as a result of
|
||||||
|
your choosing to follow a later version.
|
||||||
|
|
||||||
|
### 15. Disclaimer of Warranty
|
||||||
|
|
||||||
|
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW.
|
||||||
|
EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
|
||||||
|
PROVIDE THE PROGRAM “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER
|
||||||
|
EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
|
||||||
|
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE
|
||||||
|
QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE
|
||||||
|
DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||||
|
|
||||||
|
### 16. Limitation of Liability
|
||||||
|
|
||||||
|
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY
|
||||||
|
COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS
|
||||||
|
PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL,
|
||||||
|
INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE
|
||||||
|
PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE
|
||||||
|
OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE
|
||||||
|
WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
|
||||||
|
POSSIBILITY OF SUCH DAMAGES.
|
||||||
|
|
||||||
|
### 17. Interpretation of Sections 15 and 16
|
||||||
|
|
||||||
|
If the disclaimer of warranty and limitation of liability provided above cannot be
|
||||||
|
given local legal effect according to their terms, reviewing courts shall apply local
|
||||||
|
law that most closely approximates an absolute waiver of all civil liability in
|
||||||
|
connection with the Program, unless a warranty or assumption of liability accompanies
|
||||||
|
a copy of the Program in return for a fee.
|
||||||
|
|
||||||
|
_END OF TERMS AND CONDITIONS_
|
||||||
|
|
||||||
|
## How to Apply These Terms to Your New Programs
|
||||||
|
|
||||||
|
If you develop a new program, and you want it to be of the greatest possible use to
|
||||||
|
the public, the best way to achieve this is to make it free software which everyone
|
||||||
|
can redistribute and change under these terms.
|
||||||
|
|
||||||
|
To do so, attach the following notices to the program. It is safest to attach them
|
||||||
|
to the start of each source file to most effectively state the exclusion of warranty;
|
||||||
|
and each file should have at least the “copyright” line and a pointer to
|
||||||
|
where the full notice is found.
|
||||||
|
|
||||||
|
<one line to give the program's name and a brief idea of what it does.>
|
||||||
|
Copyright (C) <year> <name of author>
|
||||||
|
|
||||||
|
This program is free software: you can redistribute it and/or modify
|
||||||
|
it under the terms of the GNU General Public License as published by
|
||||||
|
the Free Software Foundation, either version 3 of the License, or
|
||||||
|
(at your option) any later version.
|
||||||
|
|
||||||
|
This program is distributed in the hope that it will be useful,
|
||||||
|
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||||
|
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||||
|
GNU General Public License for more details.
|
||||||
|
|
||||||
|
You should have received a copy of the GNU General Public License
|
||||||
|
along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
|
Also add information on how to contact you by electronic and paper mail.
|
||||||
|
|
||||||
|
If the program does terminal interaction, make it output a short notice like this
|
||||||
|
when it starts in an interactive mode:
|
||||||
|
|
||||||
|
<program> Copyright (C) <year> <name of author>
|
||||||
|
This program comes with ABSOLUTELY NO WARRANTY; for details type 'show w'.
|
||||||
|
This is free software, and you are welcome to redistribute it
|
||||||
|
under certain conditions; type 'show c' for details.
|
||||||
|
|
||||||
|
The hypothetical commands `show w` and `show c` should show the appropriate parts of
|
||||||
|
the General Public License. Of course, your program's commands might be different;
|
||||||
|
for a GUI interface, you would use an “about box”.
|
||||||
|
|
||||||
|
You should also get your employer (if you work as a programmer) or school, if any, to
|
||||||
|
sign a “copyright disclaimer” for the program, if necessary. For more
|
||||||
|
information on this, and how to apply and follow the GNU GPL, see
|
||||||
|
<<http://www.gnu.org/licenses/>>.
|
||||||
|
|
||||||
|
The GNU General Public License does not permit incorporating your program into
|
||||||
|
proprietary programs. If your program is a subroutine library, you may consider it
|
||||||
|
more useful to permit linking proprietary applications with the library. If this is
|
||||||
|
what you want to do, use the GNU Lesser General Public License instead of this
|
||||||
|
License. But first, please read
|
||||||
|
<<http://www.gnu.org/philosophy/why-not-lgpl.html>>.
|
17
README.md
Normal file
17
README.md
Normal file
@ -0,0 +1,17 @@
|
|||||||
|
# Installation
|
||||||
|
|
||||||
|
## Run this script:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
sudo /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/DeBrosOfficial/node/refs/heads/main/scripts/install.sh)"
|
||||||
|
```
|
||||||
|
|
||||||
|
## Stop and Clean (optional for debugging)
|
||||||
|
|
||||||
|
```bash
|
||||||
|
#!/bin/bash
|
||||||
|
|
||||||
|
sudo systemctl stop debros-node
|
||||||
|
sudo rm -rf /opt/debros-node
|
||||||
|
docker system prune -a
|
||||||
|
```
|
23
docker-compose.dev.yml
Normal file
23
docker-compose.dev.yml
Normal file
@ -0,0 +1,23 @@
|
|||||||
|
services:
|
||||||
|
debros-node-service:
|
||||||
|
build:
|
||||||
|
context: .
|
||||||
|
dockerfile: Dockerfile.dev
|
||||||
|
ports:
|
||||||
|
- '7777:7777'
|
||||||
|
restart: unless-stopped
|
||||||
|
env_file: .env
|
||||||
|
volumes:
|
||||||
|
- ./orbitdb:/app/orbitdb
|
||||||
|
- ./blockstore:/app/blockstore
|
||||||
|
- ./.env:/app/.env
|
||||||
|
- ./terms-agreement:/app/terms-agreement
|
||||||
|
environment:
|
||||||
|
- PORT=7777
|
||||||
|
# Add other environment variables if needed
|
||||||
|
networks:
|
||||||
|
- debros-network
|
||||||
|
|
||||||
|
networks:
|
||||||
|
debros-network:
|
||||||
|
driver: bridge
|
24
docker-compose.yml
Normal file
24
docker-compose.yml
Normal file
@ -0,0 +1,24 @@
|
|||||||
|
services:
|
||||||
|
debros-node-service:
|
||||||
|
build:
|
||||||
|
context: .
|
||||||
|
dockerfile: Dockerfile
|
||||||
|
ports:
|
||||||
|
- '7777:7777'
|
||||||
|
- '7778:7778'
|
||||||
|
restart: unless-stopped
|
||||||
|
env_file: .env
|
||||||
|
volumes:
|
||||||
|
- ./orbitdb:/app/orbitdb
|
||||||
|
- ./blockstore:/app/blockstore
|
||||||
|
- ./.env:/app/.env
|
||||||
|
- ./terms-agreement:/app/terms-agreement
|
||||||
|
- /var/lib/debros/keys:/var/lib/debros/keys
|
||||||
|
environment:
|
||||||
|
- PORT=7777
|
||||||
|
networks:
|
||||||
|
- debros-network
|
||||||
|
|
||||||
|
networks:
|
||||||
|
debros-network:
|
||||||
|
driver: bridge
|
250
docs/LOAD-BALANCER-TESTING.md
Normal file
250
docs/LOAD-BALANCER-TESTING.md
Normal file
@ -0,0 +1,250 @@
|
|||||||
|
# Load Balancer Testing Guide
|
||||||
|
|
||||||
|
This guide describes how to test the IPFS service discovery and load balancing system implemented in the DeBros Relay.
|
||||||
|
|
||||||
|
## Prerequisites
|
||||||
|
|
||||||
|
- Node.js and pnpm installed
|
||||||
|
- DeBros Relay codebase
|
||||||
|
- Multiple terminal windows
|
||||||
|
|
||||||
|
## Setting Up the Test Environment
|
||||||
|
|
||||||
|
### 1. Install Dependencies
|
||||||
|
|
||||||
|
First, make sure all required dependencies are installed:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
pnpm install
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2. Start Multiple Nodes
|
||||||
|
|
||||||
|
To test load balancing, you need to start multiple relay nodes with different configurations. Open separate terminal windows for each node.
|
||||||
|
|
||||||
|
**Node 1 (Primary):**
|
||||||
|
|
||||||
|
```bash
|
||||||
|
FINGERPRINT=node-1 PORT=7777 pnpm run dev
|
||||||
|
```
|
||||||
|
|
||||||
|
**Node 2:**
|
||||||
|
|
||||||
|
```bash
|
||||||
|
FINGERPRINT=node-2 PORT=6002 pnpm run dev
|
||||||
|
```
|
||||||
|
|
||||||
|
**Node 3:**
|
||||||
|
|
||||||
|
```bash
|
||||||
|
FINGERPRINT=node-3 PORT=6003 pnpm run dev
|
||||||
|
```
|
||||||
|
|
||||||
|
### 3. Verify Node Discovery
|
||||||
|
|
||||||
|
After starting the nodes, they should automatically discover each other via IPFS pubsub. Check the logs to verify that the nodes are discovering each other:
|
||||||
|
|
||||||
|
```
|
||||||
|
[SERVICE-DISCOVERY] New peer discovered: k51qzi5uqu5dl... (node-2)
|
||||||
|
[IPFS] Connected to peer: k51qzi5uqu5dl...
|
||||||
|
```
|
||||||
|
|
||||||
|
You should see periodic status reports showing connected peers:
|
||||||
|
|
||||||
|
```
|
||||||
|
==== DeBros RELAY STATUS REPORT ====
|
||||||
|
📊 Fingerprint: node-1
|
||||||
|
📊 Active connections: 3
|
||||||
|
📊 Current load: 1%
|
||||||
|
📊 Connected P2P peers: 2
|
||||||
|
==================================
|
||||||
|
CONNECTED PEERS:
|
||||||
|
1. k51qzi5uqu5dl... - Load: 5%
|
||||||
|
2. k51qzi5uqu5aa... - Load: 15%
|
||||||
|
==================================
|
||||||
|
```
|
||||||
|
|
||||||
|
## Testing Load Balancing
|
||||||
|
|
||||||
|
### 1. Using HTTP Requests
|
||||||
|
|
||||||
|
You can use the provided `load-balancer.http` file with tools like Visual Studio Code's REST Client extension or curl to test the API endpoints.
|
||||||
|
|
||||||
|
**Check Node Info:**
|
||||||
|
|
||||||
|
```
|
||||||
|
GET http://localhost:7777/api/discovery/node-info
|
||||||
|
```
|
||||||
|
|
||||||
|
**Get Optimal Peer:**
|
||||||
|
|
||||||
|
```
|
||||||
|
GET http://localhost:7777/api/discovery/optimal-peer
|
||||||
|
```
|
||||||
|
|
||||||
|
**Get All Peers:**
|
||||||
|
|
||||||
|
```
|
||||||
|
GET http://localhost:7777/api/discovery/peers
|
||||||
|
```
|
||||||
|
|
||||||
|
**Health Check:**
|
||||||
|
|
||||||
|
```
|
||||||
|
GET http://localhost:7777/health
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2. Testing Different Load Balancing Strategies
|
||||||
|
|
||||||
|
You can test different load balancing strategies by changing the environment variable:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
LOAD_BALANCING_STRATEGY=round-robin FINGERPRINT=node-1 PORT=7777 pnpm run dev
|
||||||
|
```
|
||||||
|
|
||||||
|
Available strategies:
|
||||||
|
|
||||||
|
- `least-loaded` (default): Chooses the node with the lowest load
|
||||||
|
- `round-robin`: Cycles through all available nodes
|
||||||
|
- `random`: Randomly selects a node
|
||||||
|
|
||||||
|
### 3. Simulating Load
|
||||||
|
|
||||||
|
To properly test load balancing, you need to simulate different loads on the nodes. You can do this by establishing WebSocket connections to different nodes:
|
||||||
|
|
||||||
|
**Simple WebSocket test script:**
|
||||||
|
|
||||||
|
```javascript
|
||||||
|
// save as test-connections.js
|
||||||
|
const { io } = require('socket.io-client');
|
||||||
|
|
||||||
|
const NUM_CONNECTIONS = 50; // Number of connections to create
|
||||||
|
const TARGET_PORT = 7777; // Port of the node to connect to
|
||||||
|
|
||||||
|
const connections = [];
|
||||||
|
|
||||||
|
function connect() {
|
||||||
|
for (let i = 0; i < NUM_CONNECTIONS; i++) {
|
||||||
|
const socket = io(`http://localhost:${TARGET_PORT}`, {
|
||||||
|
auth: {
|
||||||
|
walletAddress: `0x${i.toString(16).padStart(40, '0')}`,
|
||||||
|
signature: 'dummy-signature-for-testing',
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
socket.on('connect', () => {
|
||||||
|
console.log(`Connection ${i} established`);
|
||||||
|
});
|
||||||
|
|
||||||
|
connections.push(socket);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
connect();
|
||||||
|
|
||||||
|
// Keep the script running
|
||||||
|
process.stdin.resume();
|
||||||
|
|
||||||
|
// Clean up on exit
|
||||||
|
process.on('SIGINT', () => {
|
||||||
|
console.log('Closing all connections...');
|
||||||
|
connections.forEach((socket) => socket.disconnect());
|
||||||
|
process.exit();
|
||||||
|
});
|
||||||
|
```
|
||||||
|
|
||||||
|
Run this script to create connections to one of your nodes:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
node test-connections.js
|
||||||
|
```
|
||||||
|
|
||||||
|
You can modify the script to target different nodes and create varying levels of load.
|
||||||
|
|
||||||
|
### 4. Monitoring Results
|
||||||
|
|
||||||
|
As you create connections, each node should update its load metrics and broadcast this information to other nodes via pubsub. You should see log messages indicating updates to the load:
|
||||||
|
|
||||||
|
```
|
||||||
|
[LOAD-BALANCER] Current load: 30% (300 connections)
|
||||||
|
```
|
||||||
|
|
||||||
|
Then, when querying the optimal peer endpoint, you should see responses directing clients to the node with the lowest load:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"useThisNode": false,
|
||||||
|
"optimalPeer": {
|
||||||
|
"peerId": "k51qzi5uqu5dllthquketj8ds6vf0s5kkm7p3ybmzz32vr46tgqcm2sic0pxwk",
|
||||||
|
"load": 10
|
||||||
|
},
|
||||||
|
"message": "Found optimal peer"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Integrating with Client Applications
|
||||||
|
|
||||||
|
To integrate load balancing with client applications, the client should:
|
||||||
|
|
||||||
|
1. Initially connect to any known relay node
|
||||||
|
2. Query the `/api/discovery/optimal-peer` endpoint
|
||||||
|
3. If `useThisNode` is `false`, disconnect and connect to the optimal peer
|
||||||
|
4. Periodically check for better nodes (every few minutes)
|
||||||
|
|
||||||
|
**Example Client Integration:**
|
||||||
|
|
||||||
|
```javascript
|
||||||
|
async function connectToOptimalRelay() {
|
||||||
|
// Start with a known relay
|
||||||
|
const initialRelay = 'http://localhost:7777';
|
||||||
|
|
||||||
|
try {
|
||||||
|
// Query for optimal peer
|
||||||
|
const response = await fetch(`${initialRelay}/api/discovery/optimal-peer`);
|
||||||
|
const data = await response.json();
|
||||||
|
|
||||||
|
if (data.useThisNode) {
|
||||||
|
console.log(`Using initial relay: ${initialRelay}`);
|
||||||
|
return initialRelay;
|
||||||
|
} else {
|
||||||
|
// Convert peer ID to a URL (implementation depends on your setup)
|
||||||
|
const optimalRelayUrl = peerIdToUrl(data.optimalPeer.peerId);
|
||||||
|
console.log(`Switching to optimal relay: ${optimalRelayUrl}`);
|
||||||
|
return optimalRelayUrl;
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error finding optimal relay:', error);
|
||||||
|
return initialRelay; // Fall back to initial relay
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Connect to the best relay
|
||||||
|
const relayUrl = await connectToOptimalRelay();
|
||||||
|
const socket = io(relayUrl, {
|
||||||
|
auth: {
|
||||||
|
walletAddress: userWalletAddress,
|
||||||
|
signature: signature,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
```
|
||||||
|
|
||||||
|
## Troubleshooting
|
||||||
|
|
||||||
|
### Nodes Not Discovering Each Other
|
||||||
|
|
||||||
|
1. Check that the PubSub service is properly initialized
|
||||||
|
2. Verify that all nodes are using the same service discovery topic
|
||||||
|
3. Check if there are any network restrictions preventing P2P communication
|
||||||
|
4. Try setting explicit bootstrap nodes in the configuration
|
||||||
|
|
||||||
|
### High CPU/Memory Usage
|
||||||
|
|
||||||
|
1. Adjust the heartbeat interval to a higher value
|
||||||
|
2. Reduce the verbosity of logging in a production environment
|
||||||
|
3. Consider optimizing the peer discovery mechanism for larger deployments
|
||||||
|
|
||||||
|
### Load Balancing Not Working as Expected
|
||||||
|
|
||||||
|
1. Check the logs to see if load metrics are being calculated and broadcasted correctly
|
||||||
|
2. Ensure that the stale peer timeout is set appropriately
|
||||||
|
3. Try different load balancing strategies to see which works best for your use case
|
43
docs/load-balancer.http
Normal file
43
docs/load-balancer.http
Normal file
@ -0,0 +1,43 @@
|
|||||||
|
### Load Balancer and Service Discovery API
|
||||||
|
|
||||||
|
@baseUrl = http://localhost:7777/api
|
||||||
|
@contentType = application/json
|
||||||
|
|
||||||
|
### Get Node Info
|
||||||
|
# Returns information about the current node
|
||||||
|
GET {{baseUrl}}/discovery/node-info
|
||||||
|
Content-Type: {{contentType}}
|
||||||
|
|
||||||
|
### Get Optimal Peer
|
||||||
|
# Returns the optimal peer to connect to based on the load balancing strategy
|
||||||
|
GET {{baseUrl}}/discovery/optimal-peer
|
||||||
|
Content-Type: {{contentType}}
|
||||||
|
|
||||||
|
### Get All Peers
|
||||||
|
# Returns information about all connected peers
|
||||||
|
GET {{baseUrl}}/discovery/peers
|
||||||
|
Content-Type: {{contentType}}
|
||||||
|
|
||||||
|
### Health Check
|
||||||
|
# Check the health of the node and its load metrics
|
||||||
|
GET http://localhost:7777/health
|
||||||
|
Content-Type: {{contentType}}
|
||||||
|
|
||||||
|
### Multi-Node Testing Setup
|
||||||
|
|
||||||
|
## Use these commands to start multiple nodes for testing load balancing
|
||||||
|
|
||||||
|
# Start first node
|
||||||
|
# FINGERPRINT=node-1 PORT=7777 pnpm run dev
|
||||||
|
|
||||||
|
# Start second node
|
||||||
|
# FINGERPRINT=node-2 PORT=6002 pnpm run dev
|
||||||
|
|
||||||
|
# Start third node
|
||||||
|
# FINGERPRINT=node-3 PORT=6003 pnpm run dev
|
||||||
|
|
||||||
|
## Test optimal peer with second node
|
||||||
|
# GET http://localhost:6002/api/discovery/optimal-peer
|
||||||
|
|
||||||
|
## Test optimal peer with third node
|
||||||
|
# GET http://localhost:6003/api/discovery/optimal-peer
|
82
eslint.config.js
Normal file
82
eslint.config.js
Normal file
@ -0,0 +1,82 @@
|
|||||||
|
import globals from 'globals';
|
||||||
|
import js from '@eslint/js';
|
||||||
|
import tseslint from 'typescript-eslint';
|
||||||
|
import prettier from 'eslint-plugin-prettier';
|
||||||
|
|
||||||
|
export default [
|
||||||
|
// Base configuration for all files
|
||||||
|
{
|
||||||
|
files: ['**/*.{ts}'],
|
||||||
|
ignores: ['dist/**', 'docs/**', 'src/components/bot/templates/**'],
|
||||||
|
languageOptions: {
|
||||||
|
ecmaVersion: 'latest',
|
||||||
|
sourceType: 'module',
|
||||||
|
globals: {
|
||||||
|
...globals.node,
|
||||||
|
NodeJS: 'readonly', // Add NodeJS as a global
|
||||||
|
Express: 'readonly', // Add Express as a global
|
||||||
|
},
|
||||||
|
},
|
||||||
|
plugins: {
|
||||||
|
prettier: prettier,
|
||||||
|
},
|
||||||
|
rules: {
|
||||||
|
...js.configs.recommended.rules,
|
||||||
|
...prettier.configs.recommended.rules,
|
||||||
|
camelcase: 'off',
|
||||||
|
'no-invalid-this': 'off',
|
||||||
|
'prettier/prettier': 'error',
|
||||||
|
'require-jsdoc': 'off',
|
||||||
|
'valid-jsdoc': 'off',
|
||||||
|
'new-cap': ['error', { capIsNew: false }],
|
||||||
|
'no-unused-vars': [
|
||||||
|
'error',
|
||||||
|
{
|
||||||
|
argsIgnorePattern: '^_',
|
||||||
|
varsIgnorePattern: '^_',
|
||||||
|
caughtErrorsIgnorePattern: '^_',
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
|
||||||
|
// TypeScript-specific configuration
|
||||||
|
{
|
||||||
|
files: ['**/*.ts', '**/*.tsx'],
|
||||||
|
languageOptions: {
|
||||||
|
parser: tseslint.parser,
|
||||||
|
parserOptions: {
|
||||||
|
ecmaVersion: 'latest',
|
||||||
|
sourceType: 'module',
|
||||||
|
project: './tsconfig.json',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
plugins: {
|
||||||
|
'@typescript-eslint': tseslint.plugin,
|
||||||
|
},
|
||||||
|
rules: {
|
||||||
|
...tseslint.configs.recommended.rules,
|
||||||
|
'@typescript-eslint/naming-convention': [
|
||||||
|
'error',
|
||||||
|
{
|
||||||
|
selector: 'default',
|
||||||
|
format: ['camelCase', 'PascalCase', 'snake_case', 'UPPER_CASE'],
|
||||||
|
leadingUnderscore: 'allow',
|
||||||
|
trailingUnderscore: 'allow',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
selector: 'property',
|
||||||
|
format: null,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
'@typescript-eslint/no-unused-vars': [
|
||||||
|
'error',
|
||||||
|
{
|
||||||
|
argsIgnorePattern: '^_',
|
||||||
|
varsIgnorePattern: '^_',
|
||||||
|
caughtErrorsIgnorePattern: '^_',
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
];
|
98
package.json
Normal file
98
package.json
Normal file
@ -0,0 +1,98 @@
|
|||||||
|
{
|
||||||
|
"name": "@debros/node",
|
||||||
|
"type": "module",
|
||||||
|
"version": "0.0.11-alpha",
|
||||||
|
"description": "DeBros Node",
|
||||||
|
"main": "dist/index.js",
|
||||||
|
"bin": "dist/cli.js",
|
||||||
|
"pkg": {
|
||||||
|
"targets": [
|
||||||
|
"node18-linux-x64",
|
||||||
|
"node18-macos-x64",
|
||||||
|
"node18-win-x64"
|
||||||
|
],
|
||||||
|
"outputPath": "bin",
|
||||||
|
"assets": [
|
||||||
|
"dist/**/*"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"scripts": {
|
||||||
|
"dev": "npx tsx ./src/server.ts",
|
||||||
|
"dev:with-anyone": "npx tsx ./src/server.ts",
|
||||||
|
"start": "NODE_ENV=production node dist/server.js",
|
||||||
|
"lint": "npx eslint src",
|
||||||
|
"build": "npx tsc -p tsconfig.json && npx tsc-esm-fix --target=dist --outDir=dist",
|
||||||
|
"test": "NODE_ENV=test jest --coverageReporters='text-summary'",
|
||||||
|
"prepare": "husky"
|
||||||
|
},
|
||||||
|
"keywords": [],
|
||||||
|
"author": "",
|
||||||
|
"license": "ISC",
|
||||||
|
"packageManager": "pnpm@10.6.2",
|
||||||
|
"dependencies": {
|
||||||
|
"@anyone-protocol/anyone-client": "^0.4.4",
|
||||||
|
"@debros/cli": "^0.0.11-alpha",
|
||||||
|
"@debros/network": "^0.0.16-alpha",
|
||||||
|
"@helia/unixfs": "^4.0.3",
|
||||||
|
"@libp2p/bootstrap": "^11.0.32",
|
||||||
|
"@libp2p/crypto": "^5.0.15",
|
||||||
|
"@libp2p/mdns": "^11.0.32",
|
||||||
|
"@libp2p/peer-id": "^5.1.0",
|
||||||
|
"@libp2p/pubsub": "^10.1.8",
|
||||||
|
"@multiformats/multiaddr": "^12.4.0",
|
||||||
|
"cors": "^2.8.5",
|
||||||
|
"ethers": "^6.13.5",
|
||||||
|
"express": "^4.21.2",
|
||||||
|
"filesize-parser": "^1.5.1",
|
||||||
|
"helia": "^5.3.0",
|
||||||
|
"https-proxy-agent": "^7.0.6",
|
||||||
|
"libp2p": "^2.8.2",
|
||||||
|
"morgan": "^1.10.0",
|
||||||
|
"multer": "1.4.5-lts.2",
|
||||||
|
"socket.io": "^4.8.1",
|
||||||
|
"socks": "^2.8.4",
|
||||||
|
"socks-proxy-agent": "^8.0.5",
|
||||||
|
"typescript": "^5.8.2",
|
||||||
|
"uuid": "^11.1.0",
|
||||||
|
"winston": "^3.17.0",
|
||||||
|
"zod": "^3.24.2"
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"@eslint/js": "^9.23.0",
|
||||||
|
"@types/cors": "^2.8.17",
|
||||||
|
"@types/express": "^5.0.0",
|
||||||
|
"@types/filesize-parser": "^1.5.3",
|
||||||
|
"@types/morgan": "^1.9.9",
|
||||||
|
"@types/multer": "^1.4.12",
|
||||||
|
"@types/node": "^22.13.10",
|
||||||
|
"@types/node-forge": "^1.3.11",
|
||||||
|
"@types/uuid": "^10.0.0",
|
||||||
|
"@typescript-eslint/eslint-plugin": "^8.29.0",
|
||||||
|
"@typescript-eslint/parser": "^8.29.0",
|
||||||
|
"chalk": "^5.4.1",
|
||||||
|
"dotenv": "^16.4.7",
|
||||||
|
"eslint": "^9.23.0",
|
||||||
|
"eslint-plugin-prettier": "^5.2.5",
|
||||||
|
"globals": "^16.0.0",
|
||||||
|
"husky": "^9.1.7",
|
||||||
|
"inquirer": "^12.5.0",
|
||||||
|
"nodemon": "^3.1.9",
|
||||||
|
"pkg": "^5.8.1",
|
||||||
|
"prettier": "^3.5.3",
|
||||||
|
"simple-git": "^3.27.0",
|
||||||
|
"ts-node": "^10.9.2",
|
||||||
|
"tsc-esm-fix": "^3.1.2",
|
||||||
|
"typescript-eslint": "^8.29.0"
|
||||||
|
},
|
||||||
|
"pnpm": {
|
||||||
|
"ignoredBuiltDependencies": [
|
||||||
|
"@ipshipyard/node-datachannel",
|
||||||
|
"classic-level"
|
||||||
|
],
|
||||||
|
"onlyBuiltDependencies": [
|
||||||
|
"@anyone-protocol/anyone-client",
|
||||||
|
"@ipshipyard/node-datachannel",
|
||||||
|
"classic-level"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
15625
pnpm-lock.yaml
generated
Normal file
15625
pnpm-lock.yaml
generated
Normal file
File diff suppressed because it is too large
Load Diff
2
pnpm-workspace.yaml
Normal file
2
pnpm-workspace.yaml
Normal file
@ -0,0 +1,2 @@
|
|||||||
|
packages:
|
||||||
|
- 'packages/**'
|
8
scripts/build-push.sh
Normal file
8
scripts/build-push.sh
Normal file
@ -0,0 +1,8 @@
|
|||||||
|
# Define your version
|
||||||
|
VERSION="v0.0.10"
|
||||||
|
|
||||||
|
# Build and tag with both specific version and latest
|
||||||
|
docker buildx build --platform linux/amd64 \
|
||||||
|
-t debros/node:$VERSION \
|
||||||
|
-t debros/node:latest \
|
||||||
|
. --push
|
350
scripts/install.sh
Normal file
350
scripts/install.sh
Normal file
@ -0,0 +1,350 @@
|
|||||||
|
#!/bin/bash
|
||||||
|
|
||||||
|
set -e # Exit on any error
|
||||||
|
trap 'echo -e "${RED}An error occurred. Installation aborted.${NOCOLOR}"; exit 1' ERR
|
||||||
|
|
||||||
|
RED='\033[0;31m'
|
||||||
|
GREEN='\033[0;32m'
|
||||||
|
CYAN='\033[0;36m'
|
||||||
|
BLUE='\033[38;2;2;128;175m'
|
||||||
|
YELLOW='\033[1;33m'
|
||||||
|
NOCOLOR='\033[0m'
|
||||||
|
|
||||||
|
log() {
|
||||||
|
echo -e "${CYAN}[$(date '+%Y-%m-%d %H:%M:%S')]${NOCOLOR} $1"
|
||||||
|
}
|
||||||
|
|
||||||
|
. /etc/os-release
|
||||||
|
|
||||||
|
if ! command -v sudo &>/dev/null; then
|
||||||
|
log "${RED}Error: sudo command not found. Please run with sudo privileges.${NOCOLOR}"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Check ports availability
|
||||||
|
for port in 7777 7778; do
|
||||||
|
if sudo netstat -tuln | grep -q ":$port "; then
|
||||||
|
log "${RED}Error: Port $port is already in use. Please free it up and try again.${NOCOLOR}"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
done
|
||||||
|
|
||||||
|
# Check Docker installation and version
|
||||||
|
MIN_DOCKER_VERSION="20.10.0"
|
||||||
|
if ! command -v docker &> /dev/null; then
|
||||||
|
log "${CYAN}Docker not found. Installing Docker...${NOCOLOR}"
|
||||||
|
sudo apt-get update
|
||||||
|
sudo apt-get install -y apt-transport-https ca-certificates curl gnupg lsb-release
|
||||||
|
curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo gpg --dearmor -o /usr/share/keyrings/docker-archive-keyring.gpg
|
||||||
|
echo "deb [arch=$(dpkg --print-architecture) signed-by=/usr/share/keyrings/docker-archive-keyring.gpg] https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable" | sudo tee /etc/apt/sources.list.d/docker.list > /dev/null
|
||||||
|
sudo apt-get update
|
||||||
|
sudo apt-get install -y docker-ce docker-ce-cli containerd.io
|
||||||
|
sudo usermod -aG docker $USER
|
||||||
|
log "${GREEN}Docker installed successfully.${NOCOLOR}"
|
||||||
|
else
|
||||||
|
DOCKER_VERSION=$(docker --version | awk '{print $3}' | sed 's/,//')
|
||||||
|
if [ "$(printf '%s\n' "$MIN_DOCKER_VERSION" "$DOCKER_VERSION" | sort -V | head -n1)" != "$MIN_DOCKER_VERSION" ]; then
|
||||||
|
log "${RED}Docker version $DOCKER_VERSION is too old. Minimum required: $MIN_DOCKER_VERSION${NOCOLOR}"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
log "${GREEN}Docker already installed (version $DOCKER_VERSION).${NOCOLOR}"
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Check if Docker Compose is installed
|
||||||
|
if ! docker compose version &> /dev/null; then
|
||||||
|
log "${CYAN}Docker Compose not found. Installing Docker Compose...${NOCOLOR}"
|
||||||
|
sudo apt-get install -y docker-compose-plugin
|
||||||
|
log "${GREEN}Docker Compose installed successfully.${NOCOLOR}"
|
||||||
|
else
|
||||||
|
log "${GREEN}Docker Compose already installed.${NOCOLOR}"
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Create installation directory
|
||||||
|
INSTALL_DIR="/opt/debros-node"
|
||||||
|
sudo mkdir -p $INSTALL_DIR
|
||||||
|
sudo chown $USER:$USER $INSTALL_DIR
|
||||||
|
|
||||||
|
# Check if repository already exists
|
||||||
|
UPDATE_MODE=false
|
||||||
|
if [ -d "$INSTALL_DIR/.git" ]; then
|
||||||
|
log "${BLUE}==================================================${NOCOLOR}"
|
||||||
|
log "${YELLOW} DeBros Node already installed ${NOCOLOR}"
|
||||||
|
log "${BLUE}==================================================${NOCOLOR}"
|
||||||
|
|
||||||
|
echo -e "${CYAN}Do you want to update DeBros Node to the latest version?${NOCOLOR}"
|
||||||
|
read -rp "Update DeBros Node? (yes/no) [Default: yes]: " UPDATE_CHOICE
|
||||||
|
UPDATE_CHOICE="${UPDATE_CHOICE:-yes}"
|
||||||
|
|
||||||
|
if [[ "$UPDATE_CHOICE" == "yes" ]]; then
|
||||||
|
UPDATE_MODE=true
|
||||||
|
log "${BLUE}==================================================${NOCOLOR}"
|
||||||
|
log "${GREEN} Updating DeBros Node ${NOCOLOR}"
|
||||||
|
log "${BLUE}==================================================${NOCOLOR}"
|
||||||
|
|
||||||
|
if [ -f "$INSTALL_DIR/.env" ]; then
|
||||||
|
if ! cp "$INSTALL_DIR/.env" "$INSTALL_DIR/.env.backup"; then
|
||||||
|
log "${RED}Failed to create backup of .env file${NOCOLOR}"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
log "${CYAN}Backed up existing configuration.${NOCOLOR}"
|
||||||
|
fi
|
||||||
|
|
||||||
|
cd $INSTALL_DIR
|
||||||
|
git pull
|
||||||
|
|
||||||
|
log "${GREEN}DeBros Node updated successfully.${NOCOLOR}"
|
||||||
|
else
|
||||||
|
log "${CYAN}Update cancelled. Exiting...${NOCOLOR}"
|
||||||
|
exit 0
|
||||||
|
fi
|
||||||
|
else
|
||||||
|
log "${BLUE}==================================================${NOCOLOR}"
|
||||||
|
log "${GREEN} Downloading DeBros Node ${NOCOLOR}"
|
||||||
|
log "${BLUE}==================================================${NOCOLOR}"
|
||||||
|
|
||||||
|
git clone https://github.com/DeBrosOfficial/node.git $INSTALL_DIR
|
||||||
|
|
||||||
|
cd $INSTALL_DIR
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Banner
|
||||||
|
echo -e "${BLUE}========================================================================${NOCOLOR}"
|
||||||
|
echo -e "${CYAN}
|
||||||
|
____ ____ _ _ _
|
||||||
|
| _ \ ___| __ ) _ __ ___ ___ | \ | | ___ __| | ___
|
||||||
|
| | | |/ _ \ _ \| __/ _ \/ __| | \| |/ _ \ / _ |/ _ |
|
||||||
|
| |_| | __/ |_) | | | (_) \__ \ | |\ | (_) | (_| | __/
|
||||||
|
|____/ \___|____/|_| \___/|___/ |_| \_|\___/ \__,_|\___|
|
||||||
|
${NOCOLOR}"
|
||||||
|
echo -e "${BLUE}========================================================================${NOCOLOR}"
|
||||||
|
|
||||||
|
# Configuration
|
||||||
|
if [ "$UPDATE_MODE" = true ] && [ -f "$INSTALL_DIR/.env.backup" ]; then
|
||||||
|
log "${CYAN}Restoring previous configuration...${NOCOLOR}"
|
||||||
|
cp "$INSTALL_DIR/.env.backup" "$INSTALL_DIR/.env"
|
||||||
|
else
|
||||||
|
log "${BLUE}==================================================${NOCOLOR}"
|
||||||
|
log "${GREEN} Start Node Configuration Wizard ${NOCOLOR}"
|
||||||
|
log "${BLUE}==================================================${NOCOLOR}"
|
||||||
|
|
||||||
|
# Enter nickname
|
||||||
|
log "${GREEN}- Enter your desired nickname for the DeBros node (1-19 characters, only [a-zA-Z0- executing [a-zA-Z0-9] and no spaces)${NOCOLOR}"
|
||||||
|
read -rp "1/3 Enter your nickname: " NICKNAME
|
||||||
|
while [[ ! "$NICKNAME" =~ ^[a-zA-Z0-9]{1,19}$ ]]; do
|
||||||
|
log "${RED}Error: Nickname must be 1-19 characters long and contain only letters and numbers (no spaces)${NOCOLOR}"
|
||||||
|
read -rp "1/3 Enter your nickname: " NICKNAME
|
||||||
|
done
|
||||||
|
|
||||||
|
# Enter admin wallet address
|
||||||
|
log "${GREEN}- Enter your Solana wallet address to be eligible for rewards${NOCOLOR}"
|
||||||
|
read -rp "2/3 Your Solana Wallet Address: " ADMIN_WALLET
|
||||||
|
|
||||||
|
# Announce ports
|
||||||
|
log "${GREEN}- DeBros will use ports 7777 and 7778 automatically${NOCOLOR}"
|
||||||
|
|
||||||
|
# Configure firewall
|
||||||
|
log "${GREEN}- Would you like to configure the firewall to open ports 7777 and 7778?${NOCOLOR}"
|
||||||
|
read -rp "3/3 Configure firewall? (yes/no) [Default: yes]: " CONFIGURE_FIREWALL
|
||||||
|
CONFIGURE_FIREWALL="${CONFIGURE_FIREWALL:-yes}"
|
||||||
|
while ! [[ "$CONFIGURE_FIREWALL" =~ ^(yes|no)$ ]]; do
|
||||||
|
log "${RED}Error: Please respond with 'yes' or 'no'.${NOCOLOR}"
|
||||||
|
read -rp "3/3 Configure firewall? (yes/no) [Default: yes]: " CONFIGURE_FIREWALL
|
||||||
|
CONFIGURE_FIREWALL="${CONFIGURE_FIREWALL:-yes}"
|
||||||
|
done
|
||||||
|
|
||||||
|
if [[ "$CONFIGURE_FIREWALL" == "yes" ]]; then
|
||||||
|
if ! command -v ufw &> /dev/null; then
|
||||||
|
log "${GREEN}Installing UFW firewall...${NOCOLOR}"
|
||||||
|
sudo apt-get update
|
||||||
|
sudo apt-get install -y ufw
|
||||||
|
fi
|
||||||
|
|
||||||
|
log "${GREEN}Configuring firewall...${NOCOLOR}"
|
||||||
|
sudo ufw allow 7777
|
||||||
|
sudo ufw allow 7778
|
||||||
|
|
||||||
|
if [[ $(sudo ufw status) =~ "inactive" ]]; then
|
||||||
|
log "${GREEN}Enabling firewall...${NOCOLOR}"
|
||||||
|
echo "y" | sudo ufw enable
|
||||||
|
fi
|
||||||
|
|
||||||
|
log "${GREEN}Firewall configured successfully.${NOCOLOR}"
|
||||||
|
fi
|
||||||
|
|
||||||
|
KEY_DIR="/var/lib/debros/keys"
|
||||||
|
KEY_NAME="debros_key"
|
||||||
|
if [ ! -d "$KEY_DIR" ]; then
|
||||||
|
log "${CYAN}Creating folder $KEY_DIR...${NOCOLOR}"
|
||||||
|
sudo mkdir -p "$KEY_DIR"
|
||||||
|
sudo chmod 700 "$KEY_DIR"
|
||||||
|
sudo chown "$USER:$USER" "$KEY_DIR"
|
||||||
|
fi
|
||||||
|
|
||||||
|
if [ ! -f "$KEY_DIR/$KEY_NAME" ]; then
|
||||||
|
log "${CYAN}Creating new key pair...${NOCOLOR}"
|
||||||
|
ssh-keygen -t ed25519 -f "$KEY_DIR/$KEY_NAME" -N "" -q
|
||||||
|
log "${GREEN}Keys created in $KEY_DIR${NOCOLOR}"
|
||||||
|
else
|
||||||
|
log "${GREEN}Using existing keys from $KEY_DIR${NOCOLOR}"
|
||||||
|
fi
|
||||||
|
|
||||||
|
FINGERPRINT=$(ssh-keygen -l -f "$KEY_DIR/$KEY_NAME.pub" 2>/dev/null | awk '{print $2}' | sed 's/SHA256://' | base64 -d 2>/dev/null | xxd -p -u | tr -d '\n' | head -c 40)
|
||||||
|
IP_ADDRESS=$(curl -s ifconfig.me)
|
||||||
|
|
||||||
|
# Update or create .env file
|
||||||
|
if [ -f "$INSTALL_DIR/.env" ]; then
|
||||||
|
sed -i "s/NICKNAME=.*/NICKNAME=$NICKNAME/" "$INSTALL_DIR/.env"
|
||||||
|
sed -i "s/FINGERPRINT=.*/FINGERPRINT=$FINGERPRINT/" "$INSTALL_DIR/.env"
|
||||||
|
sed -i "s/HOSTNAME=.*/HOSTNAME=$IP_ADDRESS/" "$INSTALL_DIR/.env"
|
||||||
|
sed -i "s/ADMIN_WALLET=.*/ADMIN_WALLET=$ADMIN_WALLET/" "$INSTALL_DIR/.env"
|
||||||
|
sed -i "s/NODE_PUBLIC_ADDRESS=.*/NODE_PUBLIC_ADDRESS=$IP_ADDRESS/" "$INSTALL_DIR/.env"
|
||||||
|
else
|
||||||
|
cat > $INSTALL_DIR/.env << EOF
|
||||||
|
NICKNAME=$NICKNAME
|
||||||
|
FINGERPRINT=$FINGERPRINT
|
||||||
|
NODE_ENV=production
|
||||||
|
PORT=7777
|
||||||
|
ENABLE_ANYONE=true
|
||||||
|
HOSTNAME=$IP_ADDRESS
|
||||||
|
ADMIN_WALLET=$ADMIN_WALLET
|
||||||
|
ENABLE_LOAD_BALANCING=true
|
||||||
|
SERVICE_DISCOVERY_TOPIC=debros-service-discovery
|
||||||
|
HEARTBEAT_INTERVAL=5000
|
||||||
|
STALE_PEER_TIMEOUT=30000
|
||||||
|
PEER_LOG_INTERVAL=60000
|
||||||
|
NODE_PUBLIC_ADDRESS=$IP_ADDRESS
|
||||||
|
BOOTSTRAP_NODES=/ip4/188.166.113.190/tcp/7778/p2p/12D3KooWNWgs4WAUmE4CsxrL6uuyv1yuTzcRReMe5r7Psemsg2Z9,/ip4/82.208.21.140/tcp/7778/p2p/12D3KooWPUdpNX5N6dsuFAvgwfBMXUoFK2QS5sh8NpjxbfGpkSCi
|
||||||
|
MAX_CONNECTIONS=1000
|
||||||
|
LOAD_BALANCING_STRATEGY=least-loaded
|
||||||
|
ACCEPT_TERMS=true
|
||||||
|
KEY_PATH=/var/lib/debros/keys
|
||||||
|
LIBP2P_DEBUG=true
|
||||||
|
IPFS_DEBUG=true
|
||||||
|
LOG_LEVEL=debug
|
||||||
|
DEBUG=libp2p:*
|
||||||
|
EOF
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
|
||||||
|
if [ ! -f "/etc/systemd/system/debros.service" ] || [ "$UPDATE_MODE" = true ]; then
|
||||||
|
cat > /tmp/debros.service << EOF
|
||||||
|
[Unit]
|
||||||
|
Description=DeBrosNode Service
|
||||||
|
After=network.target
|
||||||
|
Wants=network-online.target
|
||||||
|
|
||||||
|
[Service]
|
||||||
|
Type=simple
|
||||||
|
User=$USER
|
||||||
|
WorkingDirectory=$INSTALL_DIR
|
||||||
|
ExecStart=/usr/bin/docker compose up --build
|
||||||
|
ExecStop=/usr/bin/docker compose down
|
||||||
|
Restart=on-failure
|
||||||
|
RestartSec=10
|
||||||
|
|
||||||
|
[Install]
|
||||||
|
WantedBy=multi-user.target
|
||||||
|
EOF
|
||||||
|
|
||||||
|
sudo mv /tmp/debros.service /etc/systemd/system/
|
||||||
|
sudo systemctl daemon-reload
|
||||||
|
if [ "$UPDATE_MODE" != true ]; then
|
||||||
|
sudo systemctl enable debros.service
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Ask about K3s installation
|
||||||
|
if ! command -v k3s &> /dev/null; then
|
||||||
|
log "${GREEN}- Would you like to install K3s for container orchestration?${NOCOLOR}"
|
||||||
|
read -rp "4/4 Install K3s? (yes/no) [Default: yes]: " INSTALL_K3S
|
||||||
|
INSTALL_K3S="${INSTALL_K3S:-yes}"
|
||||||
|
while ! [[ "$INSTALL_K3S" =~ ^(yes|no)$ ]]; do
|
||||||
|
log "${RED}Error: Please respond with 'yes' or 'no'.${NOCOLOR}"
|
||||||
|
read -rp "4/4 Install K3s? (yes/no) [Default: yes]: " INSTALL_K3S
|
||||||
|
INSTALL_K3S="${INSTALL_K3S:-yes}"
|
||||||
|
done
|
||||||
|
|
||||||
|
if [[ "$INSTALL_K3S" == "yes" ]]; then
|
||||||
|
log "${CYAN}Installing K3s...${NOCOLOR}"
|
||||||
|
curl -sfL https://get.k3s.io | sh -
|
||||||
|
|
||||||
|
# Wait for K3s to initialize
|
||||||
|
sleep 10
|
||||||
|
|
||||||
|
# Configure kubectl for the current user
|
||||||
|
sudo chmod 644 /etc/rancher/k3s/k3s.yaml
|
||||||
|
mkdir -p $HOME/.kube
|
||||||
|
sudo cp /etc/rancher/k3s/k3s.yaml $HOME/.kube/config
|
||||||
|
sudo chown $USER:$USER $HOME/.kube/config
|
||||||
|
|
||||||
|
# Install Nginx Ingress Controller
|
||||||
|
log "${CYAN}Installing Nginx Ingress Controller...${NOCOLOR}"
|
||||||
|
kubectl apply -f https://raw.githubusercontent.com/kubernetes/ingress-nginx/controller-v1.8.1/deploy/static/provider/cloud/deploy.yaml
|
||||||
|
|
||||||
|
log "${GREEN}K3s and Nginx Ingress Controller installed successfully.${NOCOLOR}"
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
|
||||||
|
chmod 600 /var/lib/debros/keys/*
|
||||||
|
chown $USER:$USER /var/lib/debros/keys/*
|
||||||
|
|
||||||
|
log "${BLUE}==================================================${NOCOLOR}"
|
||||||
|
if [ "$UPDATE_MODE" = true ]; then
|
||||||
|
log "${GREEN}Restarting DeBros Service${NOCOLOR}"
|
||||||
|
else
|
||||||
|
log "${GREEN}Starting DeBros Service${NOCOLOR}"
|
||||||
|
fi
|
||||||
|
|
||||||
|
if systemctl is-active --quiet debros.service; then
|
||||||
|
log "${CYAN}Stopping DeBros service...${NOCOLOR}"
|
||||||
|
sudo systemctl stop debros.service
|
||||||
|
sleep 2
|
||||||
|
fi
|
||||||
|
|
||||||
|
sudo systemctl start debros.service
|
||||||
|
sleep 5
|
||||||
|
|
||||||
|
if systemctl is-active --quiet debros.service; then
|
||||||
|
if [ "$UPDATE_MODE" = true ]; then
|
||||||
|
log "${GREEN}DeBros service updated and restarted successfully.${NOCOLOR}"
|
||||||
|
else
|
||||||
|
log "${GREEN}DeBros service started successfully.${NOCOLOR}"
|
||||||
|
fi
|
||||||
|
else
|
||||||
|
log "${RED}Failed to start DeBros service.${NOCOLOR}"
|
||||||
|
log "${CYAN}You can check the logs with: sudo journalctl -u debros.service${NOCOLOR}"
|
||||||
|
fi
|
||||||
|
log "${GREEN}DeBros is now running on ports: ${NOCOLOR}${CYAN}7777 and 7778${NOCOLOR}"
|
||||||
|
log "${BLUE}==================================================${NOCOLOR}"
|
||||||
|
log "${GREEN} DeBros Node Fingerprint ${NOCOLOR}"
|
||||||
|
log "${CYAN} $FINGERPRINT ${NOCOLOR}"
|
||||||
|
log "${BLUE}==================================================${NOCOLOR}"
|
||||||
|
if [ "$UPDATE_MODE" = true ]; then
|
||||||
|
log "${GREEN} Congratulations! ${NOCOLOR}"
|
||||||
|
log "${CYAN} DeBros successfully updated and restarted ${NOCOLOR}"
|
||||||
|
else
|
||||||
|
log "${GREEN} Congratulations! ${NOCOLOR}"
|
||||||
|
log "${CYAN} DeBros configuration completed successfully! ${NOCOLOR}"
|
||||||
|
fi
|
||||||
|
log "${BLUE}==================================================${NOCOLOR}"
|
||||||
|
log "${GREEN}Admin commands:${NOCOLOR}"
|
||||||
|
log "${CYAN} - sudo systemctl status debros${NOCOLOR} (Check service status)"
|
||||||
|
log "${CYAN} - sudo systemctl restart debros${NOCOLOR} (Restart service)"
|
||||||
|
log "${CYAN} - sudo journalctl -u debros.service -f${NOCOLOR} (View logs)"
|
||||||
|
log "${CYAN} - sudo systemctl stop debros${NOCOLOR} (Stop service)"
|
||||||
|
log "${CYAN} - sudo systemctl start debros${NOCOLOR} (Start service)"
|
||||||
|
log "${BLUE}==================================================${NOCOLOR}"
|
||||||
|
log "${GREEN}Installation directory: ${NOCOLOR}${CYAN}$INSTALL_DIR${NOCOLOR}"
|
||||||
|
log "${BLUE}==================================================${NOCOLOR}"
|
||||||
|
|
||||||
|
# Information about the DeBros CLI
|
||||||
|
log "${BLUE}==================================================${NOCOLOR}"
|
||||||
|
log "${GREEN}DeBros CLI Information:${NOCOLOR}"
|
||||||
|
log "${CYAN}The DeBros CLI is a tool that runs on your local development machine,${NOCOLOR}"
|
||||||
|
log "${CYAN}not on the node itself. To install it on your development machine, run:${NOCOLOR}"
|
||||||
|
log "${YELLOW}npm install -g @debros/cli${NOCOLOR} or ${YELLOW}pnpm install -g @debros/cli${NOCOLOR}"
|
||||||
|
log "${BLUE}==================================================${NOCOLOR}"
|
||||||
|
|
||||||
|
log "${GREEN}To update DeBros in the future, simply run this script again.${NOCOLOR}"
|
||||||
|
log "${CYAN}For Documentation visit https://docs.debros.io ${NOCOLOR}"
|
||||||
|
log "${BLUE}==================================================${NOCOLOR}"
|
1
scripts/openport.sh
Normal file
1
scripts/openport.sh
Normal file
@ -0,0 +1 @@
|
|||||||
|
loclx tunnel http --to localhost:7777
|
92
src/components/anyone/anyoneControllers.ts
Normal file
92
src/components/anyone/anyoneControllers.ts
Normal file
@ -0,0 +1,92 @@
|
|||||||
|
import { Request, Response } from 'express';
|
||||||
|
import { SocksProxyAgent } from 'socks-proxy-agent';
|
||||||
|
|
||||||
|
export class AnyoneController {
|
||||||
|
public async proxy(req: Request, res: Response, socksClient: any): Promise<void> {
|
||||||
|
try {
|
||||||
|
if (!socksClient) {
|
||||||
|
throw new Error('Anyone Network not initialized');
|
||||||
|
}
|
||||||
|
|
||||||
|
const { url, method, headers, body } = req.body;
|
||||||
|
|
||||||
|
if (!url) {
|
||||||
|
res.status(400).json({ error: 'URL is required' });
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log(`📡 Proxying request to: ${url}`);
|
||||||
|
|
||||||
|
// Create the SOCKS agent
|
||||||
|
const socksAgent = new SocksProxyAgent(`socks5h://127.0.0.1:${socksClient.socksPort}`);
|
||||||
|
|
||||||
|
// Special handling for Supabase requests
|
||||||
|
const requestHeaders = { ...headers };
|
||||||
|
const targetUrl = url;
|
||||||
|
const processedBody = body;
|
||||||
|
|
||||||
|
// Prepare fetch options
|
||||||
|
const fetchOptions = {
|
||||||
|
method: method || 'GET',
|
||||||
|
agent: socksAgent,
|
||||||
|
headers: requestHeaders,
|
||||||
|
body: body,
|
||||||
|
};
|
||||||
|
|
||||||
|
// Add body if it exists and method is not GET
|
||||||
|
if (processedBody && method !== 'GET' && method !== 'DELETE') {
|
||||||
|
fetchOptions.body = processedBody;
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log(`📡 Request details:`, {
|
||||||
|
url: targetUrl,
|
||||||
|
method: fetchOptions.method,
|
||||||
|
hasBody: !!fetchOptions.body,
|
||||||
|
headers: Object.keys(fetchOptions.headers),
|
||||||
|
});
|
||||||
|
|
||||||
|
// Execute the request
|
||||||
|
const response = await fetch(targetUrl, fetchOptions);
|
||||||
|
|
||||||
|
// Get response headers
|
||||||
|
const responseHeaders = Object.fromEntries(response.headers.entries());
|
||||||
|
|
||||||
|
// Get response data based on content type
|
||||||
|
const contentType = response.headers.get('content-type') || '';
|
||||||
|
let responseData;
|
||||||
|
|
||||||
|
if (contentType.includes('application/json')) {
|
||||||
|
try {
|
||||||
|
responseData = await response.json();
|
||||||
|
} catch (e: any) {
|
||||||
|
// If JSON parsing fails, fallback to text
|
||||||
|
const textData = await response.text();
|
||||||
|
console.warn('Failed to parse JSON response, returning as text:', e.message);
|
||||||
|
responseData = textData;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
responseData = await response.text();
|
||||||
|
// Try to parse as JSON anyway in case Content-Type is wrong
|
||||||
|
try {
|
||||||
|
responseData = JSON.parse(responseData);
|
||||||
|
} catch (_e) {
|
||||||
|
// Keep as text if parsing fails
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Return the response with all details
|
||||||
|
res.json({
|
||||||
|
success: true,
|
||||||
|
status: response.status,
|
||||||
|
statusText: response.statusText,
|
||||||
|
headers: responseHeaders,
|
||||||
|
response: responseData,
|
||||||
|
});
|
||||||
|
} catch (error: any) {
|
||||||
|
console.error('Proxy error:', error);
|
||||||
|
res.status(500).json({
|
||||||
|
success: false,
|
||||||
|
error: error.message || 'Error proxying request',
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
45
src/components/anyone/setup.ts
Normal file
45
src/components/anyone/setup.ts
Normal file
@ -0,0 +1,45 @@
|
|||||||
|
import { Anon, AnonSocksClient } from '@anyone-protocol/anyone-client';
|
||||||
|
import { HttpsProxyAgent } from 'https-proxy-agent';
|
||||||
|
import { config } from '../../config';
|
||||||
|
|
||||||
|
interface InitAnyoneResponse {
|
||||||
|
socksClient: AnonSocksClient | null;
|
||||||
|
proxyAgent: any;
|
||||||
|
anon: Anon | null; // Expose anon instance for later cleanup
|
||||||
|
}
|
||||||
|
|
||||||
|
export const initAnyone = async (): Promise<InitAnyoneResponse> => {
|
||||||
|
// Check if Anyone protocol is disabled in development mode
|
||||||
|
if (!config.features.enableAnyone) {
|
||||||
|
console.log('🚫 Anyone Network disabled in development mode.');
|
||||||
|
// Return mock objects to avoid errors in dependent code
|
||||||
|
return {
|
||||||
|
socksClient: null,
|
||||||
|
proxyAgent: null,
|
||||||
|
anon: null,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const anon = new Anon({
|
||||||
|
displayLog: true,
|
||||||
|
socksPort: 9060,
|
||||||
|
});
|
||||||
|
let socksClient: any;
|
||||||
|
let proxyAgent: any;
|
||||||
|
|
||||||
|
try {
|
||||||
|
await anon.start();
|
||||||
|
console.log('✅ Anyone Network connected.');
|
||||||
|
|
||||||
|
socksClient = new AnonSocksClient(anon);
|
||||||
|
proxyAgent = new HttpsProxyAgent(`socks5h://127.0.0.1:${socksClient.socksPort}`);
|
||||||
|
console.log('✅ Proxy agent initialized on port:', socksClient.socksPort);
|
||||||
|
|
||||||
|
// Do NOT stop anon here; keep it running for the proxy
|
||||||
|
} catch (err: unknown) {
|
||||||
|
console.error('❌ Error starting Anyone client:', err);
|
||||||
|
throw err; // Propagate the error to handle it upstream
|
||||||
|
}
|
||||||
|
|
||||||
|
return { socksClient, proxyAgent, anon };
|
||||||
|
};
|
52
src/components/server/healthService.ts
Normal file
52
src/components/server/healthService.ts
Normal file
@ -0,0 +1,52 @@
|
|||||||
|
import express from 'express';
|
||||||
|
import { getConnectedPeers } from '@debros/network';
|
||||||
|
import { config } from '../../config';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Registers health check endpoints
|
||||||
|
*/
|
||||||
|
export const registerHealthEndpoints = (app: express.Application) => {
|
||||||
|
// Health check endpoint that also reports node load and peers
|
||||||
|
app.get('/health', (req, res) => {
|
||||||
|
const connectedPeers = getConnectedPeers();
|
||||||
|
const peerCount = connectedPeers.length;
|
||||||
|
|
||||||
|
res.json({
|
||||||
|
status: 'healthy',
|
||||||
|
load: `10%`,
|
||||||
|
peerCount,
|
||||||
|
fingerprint: config.env.fingerprint || 'unknown',
|
||||||
|
});
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Reports status information periodically
|
||||||
|
*/
|
||||||
|
export const startStatusReporting = (interval = 600000) => {
|
||||||
|
// 10 minutes by default
|
||||||
|
// Schedule a status report every 10 minutes
|
||||||
|
return setInterval(() => {
|
||||||
|
const connectedPeers = getConnectedPeers();
|
||||||
|
const peerCount = connectedPeers.length;
|
||||||
|
|
||||||
|
console.log('==== DEBROS STATUS REPORT ====');
|
||||||
|
console.log(`📊 Fingerprint: ${config.env.fingerprint}`);
|
||||||
|
console.log(`📊 Active connections: 0`);
|
||||||
|
console.log(`📊 Current load: 10%`);
|
||||||
|
console.log(`📊 Connected P2P peers: ${peerCount}`);
|
||||||
|
console.log('==================================');
|
||||||
|
|
||||||
|
// Enhance with peer details if there are peers connected
|
||||||
|
if (peerCount > 0) {
|
||||||
|
console.log('CONNECTED PEERS:');
|
||||||
|
connectedPeers.forEach((peer, i) => {
|
||||||
|
// Adjust based on your peer structure from the new @debros/network
|
||||||
|
const peerId = peer.id || peer.toString();
|
||||||
|
const load = peer.load || 'unknown';
|
||||||
|
console.log(`${i + 1}. ${peerId.substring(0, 15)}... - Load: ${load}%`);
|
||||||
|
});
|
||||||
|
console.log('==================================');
|
||||||
|
}
|
||||||
|
}, interval);
|
||||||
|
};
|
84
src/components/server/middleware.ts
Normal file
84
src/components/server/middleware.ts
Normal file
@ -0,0 +1,84 @@
|
|||||||
|
import express from 'express';
|
||||||
|
import cors from 'cors';
|
||||||
|
import morgan from 'morgan';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Applies express middleware to the application
|
||||||
|
*/
|
||||||
|
export const applyMiddleware = (app: express.Application) => {
|
||||||
|
// CORS configuration
|
||||||
|
app.use(
|
||||||
|
cors({
|
||||||
|
origin: (origin, callback) => {
|
||||||
|
// Allow requests from your frontend in development
|
||||||
|
const allowedOrigins = ['http://localhost:4001'];
|
||||||
|
if (!origin || allowedOrigins.includes(origin)) {
|
||||||
|
callback(null, true);
|
||||||
|
} else {
|
||||||
|
callback(new Error('Not allowed by CORS'));
|
||||||
|
}
|
||||||
|
},
|
||||||
|
methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
|
||||||
|
allowedHeaders: '*',
|
||||||
|
credentials: true, // Enable credentials
|
||||||
|
})
|
||||||
|
);
|
||||||
|
|
||||||
|
// Apply HTTP request logging middleware
|
||||||
|
app.use(morgan('dev')); // Standard HTTP logging
|
||||||
|
app.use(loggingMiddleware); // Custom detailed logging
|
||||||
|
|
||||||
|
// JSON parser middleware
|
||||||
|
app.use(express.json());
|
||||||
|
|
||||||
|
// Error handling middleware
|
||||||
|
app.use(errorHandlingMiddleware);
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Custom logging middleware with detailed request/response tracking
|
||||||
|
*/
|
||||||
|
export const loggingMiddleware = (req: express.Request, res: express.Response, next: express.NextFunction) => {
|
||||||
|
const start = Date.now();
|
||||||
|
|
||||||
|
// Log request start
|
||||||
|
console.log(`[${new Date().toISOString()}] ${req.method} ${req.url} - Request started`);
|
||||||
|
|
||||||
|
// Function to log response
|
||||||
|
const logResponse = () => {
|
||||||
|
const duration = Date.now() - start;
|
||||||
|
const statusCode = res.statusCode;
|
||||||
|
const statusColor =
|
||||||
|
statusCode >= 500
|
||||||
|
? '\x1b[31m' // Red
|
||||||
|
: statusCode >= 400
|
||||||
|
? '\x1b[33m' // Yellow
|
||||||
|
: statusCode >= 300
|
||||||
|
? '\x1b[36m' // Cyan
|
||||||
|
: statusCode >= 200
|
||||||
|
? '\x1b[32m' // Green
|
||||||
|
: '\x1b[0m'; // Default
|
||||||
|
|
||||||
|
console.log(
|
||||||
|
`${statusColor}[${new Date().toISOString()}] ${req.method} ${req.url} - ${statusCode} - ${duration}ms\x1b[0m`
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
// Capture response finish event
|
||||||
|
res.on('finish', logResponse);
|
||||||
|
|
||||||
|
next();
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Global error handling middleware
|
||||||
|
*/
|
||||||
|
export const errorHandlingMiddleware = (err: any, req: express.Request, res: express.Response) => {
|
||||||
|
console.error('Unhandled error:', err);
|
||||||
|
res.status(err.status || 500).json({
|
||||||
|
error: {
|
||||||
|
message: 'An unexpected error occurred',
|
||||||
|
detail: process.env.NODE_ENV === 'development' ? err.message : undefined,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
};
|
125
src/components/server/serverService.ts
Normal file
125
src/components/server/serverService.ts
Normal file
@ -0,0 +1,125 @@
|
|||||||
|
import express from 'express';
|
||||||
|
import { createServer } from 'http';
|
||||||
|
import { initIpfs, stopIpfs, initOrbitDB, createServiceLogger, logPeersStatus } from '@debros/network'; // Import from the new package
|
||||||
|
import mainRouter from '../../routes/api';
|
||||||
|
import { applyMiddleware } from './middleware';
|
||||||
|
import { registerHealthEndpoints, startStatusReporting } from './healthService';
|
||||||
|
import { initAnyone } from '../anyone/setup';
|
||||||
|
import { config } from '../../config';
|
||||||
|
|
||||||
|
// Create loggers for different service types
|
||||||
|
const serverLogger = createServiceLogger('SERVER');
|
||||||
|
|
||||||
|
export const createApp: any = () => {
|
||||||
|
const app = express();
|
||||||
|
|
||||||
|
applyMiddleware(app);
|
||||||
|
registerHealthEndpoints(app);
|
||||||
|
app.use('/api', mainRouter);
|
||||||
|
|
||||||
|
return app;
|
||||||
|
};
|
||||||
|
|
||||||
|
export const startServer = async () => {
|
||||||
|
let anonInstance: any = null;
|
||||||
|
let statusReportInterval: NodeJS.Timeout;
|
||||||
|
let peerStatusInterval: NodeJS.Timeout;
|
||||||
|
let orbitdbInstance: any;
|
||||||
|
|
||||||
|
try {
|
||||||
|
showModeBanner();
|
||||||
|
|
||||||
|
// Initialize Anyone service
|
||||||
|
const { anon } = await initAnyone();
|
||||||
|
anonInstance = anon;
|
||||||
|
|
||||||
|
// Initialize IPFS with the new package
|
||||||
|
await initIpfs();
|
||||||
|
|
||||||
|
// Initialize OrbitDB with the new package
|
||||||
|
orbitdbInstance = await initOrbitDB();
|
||||||
|
|
||||||
|
// Create and configure Express app
|
||||||
|
const app = createApp();
|
||||||
|
const httpServer = createServer(app);
|
||||||
|
|
||||||
|
// Start the HTTP server
|
||||||
|
const port = config.env.port;
|
||||||
|
httpServer.listen(port, () => {
|
||||||
|
serverLogger.info(`Server running on port ${port}`);
|
||||||
|
|
||||||
|
// Start periodic peer status logging
|
||||||
|
peerStatusInterval = setInterval(() => {
|
||||||
|
logPeersStatus();
|
||||||
|
}, 60000); // Log status every minute
|
||||||
|
|
||||||
|
// Start status reporting
|
||||||
|
statusReportInterval = startStatusReporting();
|
||||||
|
|
||||||
|
// Setup shutdown handler after all intervals are defined
|
||||||
|
setupShutdownHandler(anonInstance, orbitdbInstance, {
|
||||||
|
statusReportInterval,
|
||||||
|
peerStatusInterval,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
serverLogger.error('Failed to initialize services:', error);
|
||||||
|
if (anonInstance) await anonInstance.stop();
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Displays the mode banner with environment information
|
||||||
|
*/
|
||||||
|
function showModeBanner() {
|
||||||
|
if (config.env.isDevelopment) {
|
||||||
|
serverLogger.info('========================================');
|
||||||
|
serverLogger.info('🚀 Running in DEVELOPMENT MODE');
|
||||||
|
serverLogger.info(`🔑 Anyone Protocol: ${config.features.enableAnyone ? 'ENABLED' : 'DISABLED'}`);
|
||||||
|
serverLogger.info(`🔖 Fingerprint: ${config.env.fingerprint}`);
|
||||||
|
serverLogger.info('========================================');
|
||||||
|
} else {
|
||||||
|
serverLogger.info('========================================');
|
||||||
|
serverLogger.info('🚀 Running in PRODUCTION MODE');
|
||||||
|
serverLogger.info(`🔑 Anyone Protocol: ${config.features.enableAnyone ? 'ENABLED' : 'DISABLED'}`);
|
||||||
|
serverLogger.info(`🔖 Fingerprint: ${config.env.fingerprint}`);
|
||||||
|
serverLogger.info('========================================');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function setupShutdownHandler(
|
||||||
|
anonInstance: any,
|
||||||
|
orbitdbInstance: any,
|
||||||
|
intervals: {
|
||||||
|
statusReportInterval: NodeJS.Timeout;
|
||||||
|
peerStatusInterval: NodeJS.Timeout;
|
||||||
|
}
|
||||||
|
) {
|
||||||
|
process.on('SIGINT', async () => {
|
||||||
|
serverLogger.info('Shutting down...');
|
||||||
|
|
||||||
|
// Clear intervals
|
||||||
|
clearInterval(intervals.statusReportInterval);
|
||||||
|
clearInterval(intervals.peerStatusInterval);
|
||||||
|
|
||||||
|
// Stop OrbitDB
|
||||||
|
serverLogger.info('Stopping OrbitDB...');
|
||||||
|
await orbitdbInstance.stop();
|
||||||
|
serverLogger.info('OrbitDB stopped.');
|
||||||
|
|
||||||
|
// Stop IPFS
|
||||||
|
serverLogger.info('Stopping IPFS...');
|
||||||
|
await stopIpfs();
|
||||||
|
serverLogger.info('IPFS stopped.');
|
||||||
|
|
||||||
|
// Stop Anyone
|
||||||
|
if (anonInstance) {
|
||||||
|
serverLogger.info('Stopping Anyone Protocol...');
|
||||||
|
await anonInstance.stop();
|
||||||
|
serverLogger.info('Anyone Protocol stopped.');
|
||||||
|
}
|
||||||
|
|
||||||
|
process.exit(0);
|
||||||
|
});
|
||||||
|
}
|
36
src/config.ts
Normal file
36
src/config.ts
Normal file
@ -0,0 +1,36 @@
|
|||||||
|
import path from 'path';
|
||||||
|
|
||||||
|
export const config = {
|
||||||
|
env: {
|
||||||
|
isDevelopment: process.env.NODE_ENV !== 'production',
|
||||||
|
port: process.env.PORT || 7777,
|
||||||
|
fingerprint: process.env.FINGERPRINT || 'default-fingerprint', // Fingerprint from .env
|
||||||
|
nickname: process.env.NICKNAME,
|
||||||
|
keyPath: process.env.KEY_PATH || '/var/lib/debros/keys',
|
||||||
|
host: process.env.HOST || '',
|
||||||
|
},
|
||||||
|
features: {
|
||||||
|
enableAnyone: process.env.ENABLE_ANYONE === 'true',
|
||||||
|
enableLoadBalancing: process.env.ENABLE_LOAD_BALANCING !== 'false',
|
||||||
|
},
|
||||||
|
ipfs: {
|
||||||
|
repo: './ipfs-repo',
|
||||||
|
swarmKey: path.resolve(process.cwd(), 'swarm.key'),
|
||||||
|
bootstrapNodes: process.env.BOOTSTRAP_NODES,
|
||||||
|
blockstorePath: path.resolve(process.cwd(), 'blockstore'),
|
||||||
|
serviceDiscovery: {
|
||||||
|
topic: process.env.SERVICE_DISCOVERY_TOPIC || 'debros-service-discovery',
|
||||||
|
heartbeatInterval: parseInt(process.env.HEARTBEAT_INTERVAL || '5000'),
|
||||||
|
staleTimeout: parseInt(process.env.STALE_PEER_TIMEOUT || '30000'),
|
||||||
|
logInterval: parseInt(process.env.PEER_LOG_INTERVAL || '60000'),
|
||||||
|
publicAddress: process.env.NODE_PUBLIC_ADDRESS || `http://localhost:${process.env.PORT || 7777}`,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
orbitdb: {
|
||||||
|
directory: path.resolve(process.cwd(), 'orbitdb/debros'),
|
||||||
|
},
|
||||||
|
loadBalancer: {
|
||||||
|
maxConnections: parseInt(process.env.MAX_CONNECTIONS || '1000'),
|
||||||
|
strategy: process.env.LOAD_BALANCING_STRATEGY || 'least-loaded',
|
||||||
|
},
|
||||||
|
};
|
35
src/routes/api.ts
Normal file
35
src/routes/api.ts
Normal file
@ -0,0 +1,35 @@
|
|||||||
|
import express, { Router, Request, Response } from 'express';
|
||||||
|
import { loadBalancerController } from '@debros/network';
|
||||||
|
|
||||||
|
const mainRouter: Router = express.Router();
|
||||||
|
|
||||||
|
// Load balancer routes (no auth required for discovery)
|
||||||
|
mainRouter.get('/discovery/node-info', loadBalancerController.getNodeInfo);
|
||||||
|
mainRouter.get('/discovery/optimal-peer', loadBalancerController.getOptimalPeer);
|
||||||
|
mainRouter.get('/discovery/peers', loadBalancerController.getAllPeers);
|
||||||
|
|
||||||
|
// Global error handler
|
||||||
|
mainRouter.use((err: any, req: Request, res: Response) => {
|
||||||
|
console.error('API Error:', err);
|
||||||
|
const statusCode = err.status || 500;
|
||||||
|
const errorResponse: any = {
|
||||||
|
error: {
|
||||||
|
message: err.message || 'Internal Server Error',
|
||||||
|
status: statusCode,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
// Add validation details if available
|
||||||
|
if (err.errors) {
|
||||||
|
errorResponse.error.details = err.errors;
|
||||||
|
}
|
||||||
|
|
||||||
|
// In production, don't send the stack trace
|
||||||
|
if (process.env.NODE_ENV !== 'production' && err.stack) {
|
||||||
|
errorResponse.error.stack = err.stack;
|
||||||
|
}
|
||||||
|
|
||||||
|
res.status(statusCode).json(errorResponse);
|
||||||
|
});
|
||||||
|
|
||||||
|
export default mainRouter;
|
25
src/server.ts
Normal file
25
src/server.ts
Normal file
@ -0,0 +1,25 @@
|
|||||||
|
import dotenv from 'dotenv';
|
||||||
|
import { config } from './config';
|
||||||
|
import { startServer } from './components/server/serverService';
|
||||||
|
import { createServiceLogger } from './utils/logger';
|
||||||
|
|
||||||
|
const logger = createServiceLogger('SERVER');
|
||||||
|
|
||||||
|
// Load environment variables from .env file
|
||||||
|
dotenv.config();
|
||||||
|
|
||||||
|
// Update config with environment variables
|
||||||
|
config.env.isDevelopment = process.env.NODE_ENV !== 'production';
|
||||||
|
config.env.port = parseInt(process.env.PORT || '7777');
|
||||||
|
config.features.enableAnyone = process.env.ENABLE_ANYONE === 'true' || process.env.NODE_ENV === 'production';
|
||||||
|
|
||||||
|
// Export default function to be called from CLI
|
||||||
|
export default startServer;
|
||||||
|
|
||||||
|
// If this script is run directly (not imported)
|
||||||
|
if (import.meta.url === `file://${process.argv[1]}`) {
|
||||||
|
startServer().catch((error) => {
|
||||||
|
logger.error('Failed to start server:', error);
|
||||||
|
process.exit(1);
|
||||||
|
});
|
||||||
|
}
|
0
src/types.d.ts
vendored
Normal file
0
src/types.d.ts
vendored
Normal file
6
src/types/express/index.d.ts
vendored
Normal file
6
src/types/express/index.d.ts
vendored
Normal file
@ -0,0 +1,6 @@
|
|||||||
|
// In a declaration file (e.g., types/express/index.d.ts)
|
||||||
|
declare namespace Express {
|
||||||
|
export interface Request {
|
||||||
|
user?: any; // Or define a more specific type for your user
|
||||||
|
}
|
||||||
|
}
|
19
src/utils/authMiddleware.ts
Normal file
19
src/utils/authMiddleware.ts
Normal file
@ -0,0 +1,19 @@
|
|||||||
|
import { Request, Response, NextFunction } from 'express';
|
||||||
|
import { ethers } from 'ethers';
|
||||||
|
|
||||||
|
export const authMiddleware = (req: Request, res: Response, next: NextFunction) => {
|
||||||
|
const walletAddress = req.headers['wallet-address'] as string;
|
||||||
|
const signature = req.headers['signature'] as string;
|
||||||
|
const message = 'Sign this message to authenticate';
|
||||||
|
|
||||||
|
try {
|
||||||
|
const recoveredAddress = ethers.verifyMessage(message, signature);
|
||||||
|
if (recoveredAddress.toLowerCase() === walletAddress.toLowerCase()) {
|
||||||
|
next(); // Το request είναι έγκυρο, συνεχίζουμε
|
||||||
|
} else {
|
||||||
|
res.status(401).json({ error: 'Unauthorized' });
|
||||||
|
}
|
||||||
|
} catch (_error) {
|
||||||
|
res.status(401).json({ error: 'Invalid signature' });
|
||||||
|
}
|
||||||
|
};
|
119
src/utils/errorHandler.ts
Normal file
119
src/utils/errorHandler.ts
Normal file
@ -0,0 +1,119 @@
|
|||||||
|
import { Request, Response, NextFunction } from 'express';
|
||||||
|
import { z } from 'zod';
|
||||||
|
import { createServiceLogger } from './logger';
|
||||||
|
|
||||||
|
const logger = createServiceLogger('ERROR');
|
||||||
|
|
||||||
|
// Error types for different HTTP status codes
|
||||||
|
export class HttpError extends Error {
|
||||||
|
status: number;
|
||||||
|
|
||||||
|
constructor(message: string, status: number = 500) {
|
||||||
|
super(message);
|
||||||
|
this.name = this.constructor.name;
|
||||||
|
this.status = status;
|
||||||
|
Error.captureStackTrace(this, this.constructor);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export class BadRequestError extends HttpError {
|
||||||
|
constructor(message: string) {
|
||||||
|
super(message, 400);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export class UnauthorizedError extends HttpError {
|
||||||
|
constructor(message: string = 'Unauthorized') {
|
||||||
|
super(message, 401);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export class ForbiddenError extends HttpError {
|
||||||
|
constructor(message: string = 'Forbidden') {
|
||||||
|
super(message, 403);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export class NotFoundError extends HttpError {
|
||||||
|
constructor(message: string = 'Resource not found') {
|
||||||
|
super(message, 404);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export class ValidationError extends BadRequestError {
|
||||||
|
errors: any[];
|
||||||
|
|
||||||
|
constructor(message: string, errors: any[]) {
|
||||||
|
super(message);
|
||||||
|
this.errors = errors;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Error handler middleware
|
||||||
|
export const errorHandler = (err: Error, req: Request, res: Response, _next: NextFunction) => {
|
||||||
|
logger.error(`Error processing ${req.method} ${req.url}:`, err);
|
||||||
|
|
||||||
|
if (err instanceof HttpError) {
|
||||||
|
// Handle custom HTTP errors
|
||||||
|
const response: any = {
|
||||||
|
error: {
|
||||||
|
message: err.message,
|
||||||
|
status: err.status,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
// Add validation errors if present
|
||||||
|
if (err instanceof ValidationError) {
|
||||||
|
response.error.details = err.errors;
|
||||||
|
}
|
||||||
|
|
||||||
|
return res.status(err.status).json(response);
|
||||||
|
} else if (err instanceof z.ZodError) {
|
||||||
|
// Handle Zod validation errors
|
||||||
|
return res.status(400).json({
|
||||||
|
error: {
|
||||||
|
message: 'Validation failed',
|
||||||
|
status: 400,
|
||||||
|
details: err.errors.map((e) => ({
|
||||||
|
path: e.path.join('.'),
|
||||||
|
message: e.message,
|
||||||
|
})),
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Handle unexpected errors
|
||||||
|
const statusCode = 500;
|
||||||
|
const isProduction = process.env.NODE_ENV === 'production';
|
||||||
|
|
||||||
|
return res.status(statusCode).json({
|
||||||
|
error: {
|
||||||
|
message: isProduction ? 'Internal server error' : err.message,
|
||||||
|
status: statusCode,
|
||||||
|
stack: isProduction ? undefined : err.stack,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
// Async route handler to catch promise rejections
|
||||||
|
export const asyncHandler = (fn: (req: Request, res: Response, next: NextFunction) => Promise<any>) => {
|
||||||
|
return (req: Request, res: Response, next: NextFunction) => {
|
||||||
|
Promise.resolve(fn(req, res, next)).catch(next);
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
// Function to handle validation with Zod
|
||||||
|
export const validateRequest = (schema: z.ZodTypeAny) => {
|
||||||
|
return (req: Request, res: Response, next: NextFunction) => {
|
||||||
|
try {
|
||||||
|
schema.parse(req.body);
|
||||||
|
next();
|
||||||
|
} catch (error) {
|
||||||
|
if (error instanceof z.ZodError) {
|
||||||
|
next(new ValidationError('Validation failed', error.errors));
|
||||||
|
} else {
|
||||||
|
next(error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
};
|
111
src/utils/logger.ts
Normal file
111
src/utils/logger.ts
Normal file
@ -0,0 +1,111 @@
|
|||||||
|
import { createLogger, format, transports } from 'winston';
|
||||||
|
import fs from 'fs';
|
||||||
|
import path from 'path';
|
||||||
|
|
||||||
|
// Create logs directory if it doesn't exist
|
||||||
|
const logsDir = path.join(process.cwd(), 'logs');
|
||||||
|
if (!fs.existsSync(logsDir)) {
|
||||||
|
fs.mkdirSync(logsDir);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Define colors for different service types
|
||||||
|
const colors: any = {
|
||||||
|
error: '\x1b[31m', // red
|
||||||
|
warn: '\x1b[33m', // yellow
|
||||||
|
info: '\x1b[32m', // green
|
||||||
|
debug: '\x1b[36m', // cyan
|
||||||
|
reset: '\x1b[0m', // reset
|
||||||
|
|
||||||
|
// Service specific colors
|
||||||
|
IPFS: '\x1b[36m', // cyan
|
||||||
|
HEARTBEAT: '\x1b[33m', // yellow
|
||||||
|
SOCKET: '\x1b[34m', // blue
|
||||||
|
'LOAD-BALANCER': '\x1b[35m', // magenta
|
||||||
|
DEFAULT: '\x1b[37m', // white
|
||||||
|
};
|
||||||
|
|
||||||
|
// Custom format for console output with colors
|
||||||
|
const customConsoleFormat = format.printf(({ level, message, timestamp, service }: any) => {
|
||||||
|
// Truncate error messages
|
||||||
|
if (level === 'error' && typeof message === 'string' && message.length > 300) {
|
||||||
|
message = message.substring(0, 300) + '... [truncated]';
|
||||||
|
}
|
||||||
|
|
||||||
|
// Handle objects and errors
|
||||||
|
if (typeof message === 'object' && message !== null) {
|
||||||
|
if (message instanceof Error) {
|
||||||
|
message = message.message;
|
||||||
|
// Truncate error messages
|
||||||
|
if (message.length > 300) {
|
||||||
|
message = message.substring(0, 300) + '... [truncated]';
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
try {
|
||||||
|
message = JSON.stringify(message, null, 2);
|
||||||
|
} catch (_e) {
|
||||||
|
message = '[Object]';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const serviceColor = service && colors[service] ? colors[service] : colors.DEFAULT;
|
||||||
|
const levelColor = colors[level] || colors.DEFAULT;
|
||||||
|
const serviceTag = service ? `[${service}]` : '';
|
||||||
|
|
||||||
|
return `${timestamp} ${levelColor}${level}${colors.reset}: ${serviceColor}${serviceTag}${colors.reset} ${message}`;
|
||||||
|
});
|
||||||
|
|
||||||
|
// Custom format for file output (no colors)
|
||||||
|
const customFileFormat = format.printf(({ level, message, timestamp, service }) => {
|
||||||
|
// Handle objects and errors
|
||||||
|
if (typeof message === 'object' && message !== null) {
|
||||||
|
if (message instanceof Error) {
|
||||||
|
message = message.message;
|
||||||
|
} else {
|
||||||
|
try {
|
||||||
|
message = JSON.stringify(message);
|
||||||
|
} catch (_e) {
|
||||||
|
message = '[Object]';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const serviceTag = service ? `[${service}]` : '';
|
||||||
|
return `${timestamp} ${level}: ${serviceTag} ${message}`;
|
||||||
|
});
|
||||||
|
|
||||||
|
// Create the logger
|
||||||
|
const logger = createLogger({
|
||||||
|
level: process.env.LOG_LEVEL || 'info',
|
||||||
|
format: format.combine(format.timestamp({ format: 'YYYY-MM-DD HH:mm:ss' }), format.splat()),
|
||||||
|
defaultMeta: { service: 'DEFAULT' },
|
||||||
|
transports: [
|
||||||
|
// Console transport
|
||||||
|
new transports.Console({
|
||||||
|
format: format.combine(format.timestamp({ format: 'YYYY-MM-DD HH:mm:ss' }), customConsoleFormat),
|
||||||
|
}),
|
||||||
|
// Combined log file
|
||||||
|
new transports.File({
|
||||||
|
filename: path.join(logsDir, 'app.log'),
|
||||||
|
format: format.combine(format.timestamp({ format: 'YYYY-MM-DD HH:mm:ss' }), customFileFormat),
|
||||||
|
}),
|
||||||
|
// Error log file
|
||||||
|
new transports.File({
|
||||||
|
filename: path.join(logsDir, 'error.log'),
|
||||||
|
level: 'error',
|
||||||
|
format: format.combine(format.timestamp({ format: 'YYYY-MM-DD HH:mm:ss' }), customFileFormat),
|
||||||
|
}),
|
||||||
|
],
|
||||||
|
});
|
||||||
|
|
||||||
|
// Helper function to create a logger for a specific service
|
||||||
|
export const createServiceLogger = (serviceName: string) => {
|
||||||
|
return {
|
||||||
|
error: (message: any, ...meta: any[]) => logger.error(message, { service: serviceName, ...meta }),
|
||||||
|
warn: (message: any, ...meta: any[]) => logger.warn(message, { service: serviceName, ...meta }),
|
||||||
|
info: (message: any, ...meta: any[]) => logger.info(message, { service: serviceName, ...meta }),
|
||||||
|
debug: (message: any, ...meta: any[]) => logger.debug(message, { service: serviceName, ...meta }),
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
export default logger;
|
1
terms-agreement
Normal file
1
terms-agreement
Normal file
@ -0,0 +1 @@
|
|||||||
|
agreed
|
58
tsconfig.json
Normal file
58
tsconfig.json
Normal file
@ -0,0 +1,58 @@
|
|||||||
|
{
|
||||||
|
"$schema": "https://json.schemastore.org/tsconfig",
|
||||||
|
"display": "Node 20",
|
||||||
|
"compilerOptions": {
|
||||||
|
/* Specify what module code is generated. */
|
||||||
|
"module": "ES2020",
|
||||||
|
/* Specify which ECMAScript version the project's output JavaScript code must support.*/
|
||||||
|
"target": "ESNext",
|
||||||
|
/*
|
||||||
|
* Specify how TypeScript looks up a file from a given module specifier.
|
||||||
|
* Bundler removes the need to specify the full path inside imports
|
||||||
|
*/
|
||||||
|
"moduleResolution": "bundler",
|
||||||
|
/* Skip type checking of declaration files. */
|
||||||
|
"skipLibCheck": true,
|
||||||
|
/* Removes comments from the project's output JavaScript code. */
|
||||||
|
"removeComments": true,
|
||||||
|
/* Enables experimental support for emitting type metadata for decorators which works with the module reflect-metadata. */
|
||||||
|
"emitDecoratorMetadata": true,
|
||||||
|
/* Enables experimental support for decorators, which is a version of decorators that predates the TC39 standardization process. */
|
||||||
|
"experimentalDecorators": true,
|
||||||
|
/* When set, TypeScript will include the original content of the .ts file as an embedded string in the source map (using the source map's sourcesContent property). This is often useful in the same cases as inlineSourceMap. */
|
||||||
|
"inlineSources": true,
|
||||||
|
/* Enables the generation of sourcemap files. */
|
||||||
|
"sourceMap": true,
|
||||||
|
/* Allow JavaScript files to be imported inside the project, instead of just .ts and .tsx files. */
|
||||||
|
"allowJs": true,
|
||||||
|
/* By default (with esModuleInterop false or not set) TypeScript treats CommonJS/AMD/UMD modules similar to ES6 modules. */
|
||||||
|
"esModuleInterop": true,
|
||||||
|
/* The strict flag enables a wide range of type checking behavior that results in stronger guarantees of program correctness. */
|
||||||
|
"strict": true,
|
||||||
|
/* When set to true, TypeScript will raise an error when a class property was declared but not set in the constructor. */
|
||||||
|
"strictPropertyInitialization": false,
|
||||||
|
/* This flag controls how import works */
|
||||||
|
"importsNotUsedAsValues": "remove",
|
||||||
|
/* Specify the location where a debugger should locate TypeScript files instead of relative source locations */
|
||||||
|
"sourceRoot": "/",
|
||||||
|
/* The longest common path of all non-declaration input files. */
|
||||||
|
"rootDir": "src",
|
||||||
|
/* Directory name of the project's output JavaScript code. */
|
||||||
|
"outDir": "dist",
|
||||||
|
/* Specify to generate .d.ts files for every TypeScript or JavaScript file inside the project. */
|
||||||
|
"declaration": true,
|
||||||
|
/* Sets a base directory from which to resolve non-relative module names. */
|
||||||
|
"baseUrl": "."
|
||||||
|
/* A series of entries which re-map imports to lookup locations relative to the baseUrl if set, or to the tsconfig file itself otherwise. */
|
||||||
|
// "paths": {
|
||||||
|
// "@/*": [
|
||||||
|
// "./src/*"
|
||||||
|
// ]
|
||||||
|
// },
|
||||||
|
},
|
||||||
|
"include": ["src/**/*"],
|
||||||
|
"exclude": ["coverage", "dist", "eslint.config.js", "node_modules"],
|
||||||
|
"ts-node": {
|
||||||
|
"esm": true
|
||||||
|
}
|
||||||
|
}
|
Loading…
x
Reference in New Issue
Block a user