Runway 1.0.0
This commit is contained in:
commit
dcf819146b
1372 files changed
+188168
No files matched your search
@@ -0,0 +1,10 @@
|
||||
# Changelog
|
||||
|
||||
All notable changes are recorded here. Versions follow [Semantic Versioning](https://semver.org/).
|
||||
|
||||
## [3.3.0] — 2026-10-21
|
||||
|
||||
First public release of `search-lucene`: an Apache Lucene engine for the `search` plugin — one index per site and
|
||||
language, language analyzers (stemming), tiered ranking over BM25, fuzzy matching and highlighting. Requires SPI `1.0.0` (Runway `1.0.0` or later),
|
||||
`search >= 2.2.0` and `lucene-provider == 10.4.0`. Licensed under the GNU AGPL v3.0 with an additional permission for
|
||||
plugins (`LICENSE`, `LICENSE-EXCEPTION`).
|
||||
@@ -0,0 +1,661 @@
|
||||
GNU AFFERO GENERAL PUBLIC LICENSE
|
||||
Version 3, 19 November 2007
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
Preamble
|
||||
|
||||
The GNU Affero General Public License is a free, copyleft license for
|
||||
software and other kinds of works, specifically designed to ensure
|
||||
cooperation with the community in the case of network server software.
|
||||
|
||||
The licenses for most software and other practical works are designed
|
||||
to take away your freedom to share and change the works. By contrast,
|
||||
our General Public Licenses are intended to guarantee your freedom to
|
||||
share and change all versions of a program--to make sure it remains free
|
||||
software for all its users.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not
|
||||
price. Our General Public Licenses are designed to make sure that you
|
||||
have the freedom to distribute copies of free software (and charge for
|
||||
them if you wish), that you receive source code or can get it if you
|
||||
want it, that you can change the software or use pieces of it in new
|
||||
free programs, and that you know you can do these things.
|
||||
|
||||
Developers that use our General Public Licenses protect your rights
|
||||
with two steps: (1) assert copyright on the software, and (2) offer
|
||||
you this License which gives you legal permission to copy, distribute
|
||||
and/or modify the software.
|
||||
|
||||
A secondary benefit of defending all users' freedom is that
|
||||
improvements made in alternate versions of the program, if they
|
||||
receive widespread use, become available for other developers to
|
||||
incorporate. Many developers of free software are heartened and
|
||||
encouraged by the resulting cooperation. However, in the case of
|
||||
software used on network servers, this result may fail to come about.
|
||||
The GNU General Public License permits making a modified version and
|
||||
letting the public access it on a server without ever releasing its
|
||||
source code to the public.
|
||||
|
||||
The GNU Affero General Public License is designed specifically to
|
||||
ensure that, in such cases, the modified source code becomes available
|
||||
to the community. It requires the operator of a network server to
|
||||
provide the source code of the modified version running there to the
|
||||
users of that server. Therefore, public use of a modified version, on
|
||||
a publicly accessible server, gives the public access to the source
|
||||
code of the modified version.
|
||||
|
||||
An older license, called the Affero General Public License and
|
||||
published by Affero, was designed to accomplish similar goals. This is
|
||||
a different license, not a version of the Affero GPL, but Affero has
|
||||
released a new version of the Affero GPL which permits relicensing under
|
||||
this license.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow.
|
||||
|
||||
TERMS AND CONDITIONS
|
||||
|
||||
0. Definitions.
|
||||
|
||||
"This License" refers to version 3 of the GNU Affero General Public License.
|
||||
|
||||
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||
works, such as semiconductor masks.
|
||||
|
||||
"The Program" refers to any copyrightable work licensed under this
|
||||
License. Each licensee is addressed as "you". "Licensees" and
|
||||
"recipients" may be individuals or organizations.
|
||||
|
||||
To "modify" a work means to copy from or adapt all or part of the work
|
||||
in a fashion requiring copyright permission, other than the making of an
|
||||
exact copy. The resulting work is called a "modified version" of the
|
||||
earlier work or a work "based on" the earlier work.
|
||||
|
||||
A "covered work" means either the unmodified Program or a work based
|
||||
on the Program.
|
||||
|
||||
To "propagate" a work means to do anything with it that, without
|
||||
permission, would make you directly or secondarily liable for
|
||||
infringement under applicable copyright law, except executing it on a
|
||||
computer or modifying a private copy. Propagation includes copying,
|
||||
distribution (with or without modification), making available to the
|
||||
public, and in some countries other activities as well.
|
||||
|
||||
To "convey" a work means any kind of propagation that enables other
|
||||
parties to make or receive copies. Mere interaction with a user through
|
||||
a computer network, with no transfer of a copy, is not conveying.
|
||||
|
||||
An interactive user interface displays "Appropriate Legal Notices"
|
||||
to the extent that it includes a convenient and prominently visible
|
||||
feature that (1) displays an appropriate copyright notice, and (2)
|
||||
tells the user that there is no warranty for the work (except to the
|
||||
extent that warranties are provided), that licensees may convey the
|
||||
work under this License, and how to view a copy of this License. If
|
||||
the interface presents a list of user commands or options, such as a
|
||||
menu, a prominent item in the list meets this criterion.
|
||||
|
||||
1. Source Code.
|
||||
|
||||
The "source code" for a work means the preferred form of the work
|
||||
for making modifications to it. "Object code" means any non-source
|
||||
form of a work.
|
||||
|
||||
A "Standard Interface" means an interface that either is an official
|
||||
standard defined by a recognized standards body, or, in the case of
|
||||
interfaces specified for a particular programming language, one that
|
||||
is widely used among developers working in that language.
|
||||
|
||||
The "System Libraries" of an executable work include anything, other
|
||||
than the work as a whole, that (a) is included in the normal form of
|
||||
packaging a Major Component, but which is not part of that Major
|
||||
Component, and (b) serves only to enable use of the work with that
|
||||
Major Component, or to implement a Standard Interface for which an
|
||||
implementation is available to the public in source code form. A
|
||||
"Major Component", in this context, means a major essential component
|
||||
(kernel, window system, and so on) of the specific operating system
|
||||
(if any) on which the executable work runs, or a compiler used to
|
||||
produce the work, or an object code interpreter used to run it.
|
||||
|
||||
The "Corresponding Source" for a work in object code form means all
|
||||
the source code needed to generate, install, and (for an executable
|
||||
work) run the object code and to modify the work, including scripts to
|
||||
control those activities. However, it does not include the work's
|
||||
System Libraries, or general-purpose tools or generally available free
|
||||
programs which are used unmodified in performing those activities but
|
||||
which are not part of the work. For example, Corresponding Source
|
||||
includes interface definition files associated with source files for
|
||||
the work, and the source code for shared libraries and dynamically
|
||||
linked subprograms that the work is specifically designed to require,
|
||||
such as by intimate data communication or control flow between those
|
||||
subprograms and other parts of the work.
|
||||
|
||||
The Corresponding Source need not include anything that users
|
||||
can regenerate automatically from other parts of the Corresponding
|
||||
Source.
|
||||
|
||||
The Corresponding Source for a work in source code form is that
|
||||
same work.
|
||||
|
||||
2. Basic Permissions.
|
||||
|
||||
All rights granted under this License are granted for the term of
|
||||
copyright on the Program, and are irrevocable provided the stated
|
||||
conditions are met. This License explicitly affirms your unlimited
|
||||
permission to run the unmodified Program. The output from running a
|
||||
covered work is covered by this License only if the output, given its
|
||||
content, constitutes a covered work. This License acknowledges your
|
||||
rights of fair use or other equivalent, as provided by copyright law.
|
||||
|
||||
You may make, run and propagate covered works that you do not
|
||||
convey, without conditions so long as your license otherwise remains
|
||||
in force. You may convey covered works to others for the sole purpose
|
||||
of having them make modifications exclusively for you, or provide you
|
||||
with facilities for running those works, provided that you comply with
|
||||
the terms of this License in conveying all material for which you do
|
||||
not control copyright. Those thus making or running the covered works
|
||||
for you must do so exclusively on your behalf, under your direction
|
||||
and control, on terms that prohibit them from making any copies of
|
||||
your copyrighted material outside their relationship with you.
|
||||
|
||||
Conveying under any other circumstances is permitted solely under
|
||||
the conditions stated below. Sublicensing is not allowed; section 10
|
||||
makes it unnecessary.
|
||||
|
||||
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||
|
||||
No covered work shall be deemed part of an effective technological
|
||||
measure under any applicable law fulfilling obligations under article
|
||||
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||
similar laws prohibiting or restricting circumvention of such
|
||||
measures.
|
||||
|
||||
When you convey a covered work, you waive any legal power to forbid
|
||||
circumvention of technological measures to the extent such circumvention
|
||||
is effected by exercising rights under this License with respect to
|
||||
the covered work, and you disclaim any intention to limit operation or
|
||||
modification of the work as a means of enforcing, against the work's
|
||||
users, your or third parties' legal rights to forbid circumvention of
|
||||
technological measures.
|
||||
|
||||
4. Conveying Verbatim Copies.
|
||||
|
||||
You may convey verbatim copies of the Program's source code as you
|
||||
receive it, in any medium, provided that you conspicuously and
|
||||
appropriately publish on each copy an appropriate copyright notice;
|
||||
keep intact all notices stating that this License and any
|
||||
non-permissive terms added in accord with section 7 apply to the code;
|
||||
keep intact all notices of the absence of any warranty; and give all
|
||||
recipients a copy of this License along with the Program.
|
||||
|
||||
You may charge any price or no price for each copy that you convey,
|
||||
and you may offer support or warranty protection for a fee.
|
||||
|
||||
5. Conveying Modified Source Versions.
|
||||
|
||||
You may convey a work based on the Program, or the modifications to
|
||||
produce it from the Program, in the form of source code under the
|
||||
terms of section 4, provided that you also meet all of these conditions:
|
||||
|
||||
a) The work must carry prominent notices stating that you modified
|
||||
it, and giving a relevant date.
|
||||
|
||||
b) The work must carry prominent notices stating that it is
|
||||
released under this License and any conditions added under section
|
||||
7. This requirement modifies the requirement in section 4 to
|
||||
"keep intact all notices".
|
||||
|
||||
c) You must license the entire work, as a whole, under this
|
||||
License to anyone who comes into possession of a copy. This
|
||||
License will therefore apply, along with any applicable section 7
|
||||
additional terms, to the whole of the work, and all its parts,
|
||||
regardless of how they are packaged. This License gives no
|
||||
permission to license the work in any other way, but it does not
|
||||
invalidate such permission if you have separately received it.
|
||||
|
||||
d) If the work has interactive user interfaces, each must display
|
||||
Appropriate Legal Notices; however, if the Program has interactive
|
||||
interfaces that do not display Appropriate Legal Notices, your
|
||||
work need not make them do so.
|
||||
|
||||
A compilation of a covered work with other separate and independent
|
||||
works, which are not by their nature extensions of the covered work,
|
||||
and which are not combined with it such as to form a larger program,
|
||||
in or on a volume of a storage or distribution medium, is called an
|
||||
"aggregate" if the compilation and its resulting copyright are not
|
||||
used to limit the access or legal rights of the compilation's users
|
||||
beyond what the individual works permit. Inclusion of a covered work
|
||||
in an aggregate does not cause this License to apply to the other
|
||||
parts of the aggregate.
|
||||
|
||||
6. Conveying Non-Source Forms.
|
||||
|
||||
You may convey a covered work in object code form under the terms
|
||||
of sections 4 and 5, provided that you also convey the
|
||||
machine-readable Corresponding Source under the terms of this License,
|
||||
in one of these ways:
|
||||
|
||||
a) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by the
|
||||
Corresponding Source fixed on a durable physical medium
|
||||
customarily used for software interchange.
|
||||
|
||||
b) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by a
|
||||
written offer, valid for at least three years and valid for as
|
||||
long as you offer spare parts or customer support for that product
|
||||
model, to give anyone who possesses the object code either (1) a
|
||||
copy of the Corresponding Source for all the software in the
|
||||
product that is covered by this License, on a durable physical
|
||||
medium customarily used for software interchange, for a price no
|
||||
more than your reasonable cost of physically performing this
|
||||
conveying of source, or (2) access to copy the
|
||||
Corresponding Source from a network server at no charge.
|
||||
|
||||
c) Convey individual copies of the object code with a copy of the
|
||||
written offer to provide the Corresponding Source. This
|
||||
alternative is allowed only occasionally and noncommercially, and
|
||||
only if you received the object code with such an offer, in accord
|
||||
with subsection 6b.
|
||||
|
||||
d) Convey the object code by offering access from a designated
|
||||
place (gratis or for a charge), and offer equivalent access to the
|
||||
Corresponding Source in the same way through the same place at no
|
||||
further charge. You need not require recipients to copy the
|
||||
Corresponding Source along with the object code. If the place to
|
||||
copy the object code is a network server, the Corresponding Source
|
||||
may be on a different server (operated by you or a third party)
|
||||
that supports equivalent copying facilities, provided you maintain
|
||||
clear directions next to the object code saying where to find the
|
||||
Corresponding Source. Regardless of what server hosts the
|
||||
Corresponding Source, you remain obligated to ensure that it is
|
||||
available for as long as needed to satisfy these requirements.
|
||||
|
||||
e) Convey the object code using peer-to-peer transmission, provided
|
||||
you inform other peers where the object code and Corresponding
|
||||
Source of the work are being offered to the general public at no
|
||||
charge under subsection 6d.
|
||||
|
||||
A separable portion of the object code, whose source code is excluded
|
||||
from the Corresponding Source as a System Library, need not be
|
||||
included in conveying the object code work.
|
||||
|
||||
A "User Product" is either (1) a "consumer product", which means any
|
||||
tangible personal property which is normally used for personal, family,
|
||||
or household purposes, or (2) anything designed or sold for incorporation
|
||||
into a dwelling. In determining whether a product is a consumer product,
|
||||
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||
product received by a particular user, "normally used" refers to a
|
||||
typical or common use of that class of product, regardless of the status
|
||||
of the particular user or of the way in which the particular user
|
||||
actually uses, or expects or is expected to use, the product. A product
|
||||
is a consumer product regardless of whether the product has substantial
|
||||
commercial, industrial or non-consumer uses, unless such uses represent
|
||||
the only significant mode of use of the product.
|
||||
|
||||
"Installation Information" for a User Product means any methods,
|
||||
procedures, authorization keys, or other information required to install
|
||||
and execute modified versions of a covered work in that User Product from
|
||||
a modified version of its Corresponding Source. The information must
|
||||
suffice to ensure that the continued functioning of the modified object
|
||||
code is in no case prevented or interfered with solely because
|
||||
modification has been made.
|
||||
|
||||
If you convey an object code work under this section in, or with, or
|
||||
specifically for use in, a User Product, and the conveying occurs as
|
||||
part of a transaction in which the right of possession and use of the
|
||||
User Product is transferred to the recipient in perpetuity or for a
|
||||
fixed term (regardless of how the transaction is characterized), the
|
||||
Corresponding Source conveyed under this section must be accompanied
|
||||
by the Installation Information. But this requirement does not apply
|
||||
if neither you nor any third party retains the ability to install
|
||||
modified object code on the User Product (for example, the work has
|
||||
been installed in ROM).
|
||||
|
||||
The requirement to provide Installation Information does not include a
|
||||
requirement to continue to provide support service, warranty, or updates
|
||||
for a work that has been modified or installed by the recipient, or for
|
||||
the User Product in which it has been modified or installed. Access to a
|
||||
network may be denied when the modification itself materially and
|
||||
adversely affects the operation of the network or violates the rules and
|
||||
protocols for communication across the network.
|
||||
|
||||
Corresponding Source conveyed, and Installation Information provided,
|
||||
in accord with this section must be in a format that is publicly
|
||||
documented (and with an implementation available to the public in
|
||||
source code form), and must require no special password or key for
|
||||
unpacking, reading or copying.
|
||||
|
||||
7. Additional Terms.
|
||||
|
||||
"Additional permissions" are terms that supplement the terms of this
|
||||
License by making exceptions from one or more of its conditions.
|
||||
Additional permissions that are applicable to the entire Program shall
|
||||
be treated as though they were included in this License, to the extent
|
||||
that they are valid under applicable law. If additional permissions
|
||||
apply only to part of the Program, that part may be used separately
|
||||
under those permissions, but the entire Program remains governed by
|
||||
this License without regard to the additional permissions.
|
||||
|
||||
When you convey a copy of a covered work, you may at your option
|
||||
remove any additional permissions from that copy, or from any part of
|
||||
it. (Additional permissions may be written to require their own
|
||||
removal in certain cases when you modify the work.) You may place
|
||||
additional permissions on material, added by you to a covered work,
|
||||
for which you have or can give appropriate copyright permission.
|
||||
|
||||
Notwithstanding any other provision of this License, for material you
|
||||
add to a covered work, you may (if authorized by the copyright holders of
|
||||
that material) supplement the terms of this License with terms:
|
||||
|
||||
a) Disclaiming warranty or limiting liability differently from the
|
||||
terms of sections 15 and 16 of this License; or
|
||||
|
||||
b) Requiring preservation of specified reasonable legal notices or
|
||||
author attributions in that material or in the Appropriate Legal
|
||||
Notices displayed by works containing it; or
|
||||
|
||||
c) Prohibiting misrepresentation of the origin of that material, or
|
||||
requiring that modified versions of such material be marked in
|
||||
reasonable ways as different from the original version; or
|
||||
|
||||
d) Limiting the use for publicity purposes of names of licensors or
|
||||
authors of the material; or
|
||||
|
||||
e) Declining to grant rights under trademark law for use of some
|
||||
trade names, trademarks, or service marks; or
|
||||
|
||||
f) Requiring indemnification of licensors and authors of that
|
||||
material by anyone who conveys the material (or modified versions of
|
||||
it) with contractual assumptions of liability to the recipient, for
|
||||
any liability that these contractual assumptions directly impose on
|
||||
those licensors and authors.
|
||||
|
||||
All other non-permissive additional terms are considered "further
|
||||
restrictions" within the meaning of section 10. If the Program as you
|
||||
received it, or any part of it, contains a notice stating that it is
|
||||
governed by this License along with a term that is a further
|
||||
restriction, you may remove that term. If a license document contains
|
||||
a further restriction but permits relicensing or conveying under this
|
||||
License, you may add to a covered work material governed by the terms
|
||||
of that license document, provided that the further restriction does
|
||||
not survive such relicensing or conveying.
|
||||
|
||||
If you add terms to a covered work in accord with this section, you
|
||||
must place, in the relevant source files, a statement of the
|
||||
additional terms that apply to those files, or a notice indicating
|
||||
where to find the applicable terms.
|
||||
|
||||
Additional terms, permissive or non-permissive, may be stated in the
|
||||
form of a separately written license, or stated as exceptions;
|
||||
the above requirements apply either way.
|
||||
|
||||
8. Termination.
|
||||
|
||||
You may not propagate or modify a covered work except as expressly
|
||||
provided under this License. Any attempt otherwise to propagate or
|
||||
modify it is void, and will automatically terminate your rights under
|
||||
this License (including any patent licenses granted under the third
|
||||
paragraph of section 11).
|
||||
|
||||
However, if you cease all violation of this License, then your
|
||||
license from a particular copyright holder is reinstated (a)
|
||||
provisionally, unless and until the copyright holder explicitly and
|
||||
finally terminates your license, and (b) permanently, if the copyright
|
||||
holder fails to notify you of the violation by some reasonable means
|
||||
prior to 60 days after the cessation.
|
||||
|
||||
Moreover, your license from a particular copyright holder is
|
||||
reinstated permanently if the copyright holder notifies you of the
|
||||
violation by some reasonable means, this is the first time you have
|
||||
received notice of violation of this License (for any work) from that
|
||||
copyright holder, and you cure the violation prior to 30 days after
|
||||
your receipt of the notice.
|
||||
|
||||
Termination of your rights under this section does not terminate the
|
||||
licenses of parties who have received copies or rights from you under
|
||||
this License. If your rights have been terminated and not permanently
|
||||
reinstated, you do not qualify to receive new licenses for the same
|
||||
material under section 10.
|
||||
|
||||
9. Acceptance Not Required for Having Copies.
|
||||
|
||||
You are not required to accept this License in order to receive or
|
||||
run a copy of the Program. Ancillary propagation of a covered work
|
||||
occurring solely as a consequence of using peer-to-peer transmission
|
||||
to receive a copy likewise does not require acceptance. However,
|
||||
nothing other than this License grants you permission to propagate or
|
||||
modify any covered work. These actions infringe copyright if you do
|
||||
not accept this License. Therefore, by modifying or propagating a
|
||||
covered work, you indicate your acceptance of this License to do so.
|
||||
|
||||
10. Automatic Licensing of Downstream Recipients.
|
||||
|
||||
Each time you convey a covered work, the recipient automatically
|
||||
receives a license from the original licensors, to run, modify and
|
||||
propagate that work, subject to this License. You are not responsible
|
||||
for enforcing compliance by third parties with this License.
|
||||
|
||||
An "entity transaction" is a transaction transferring control of an
|
||||
organization, or substantially all assets of one, or subdividing an
|
||||
organization, or merging organizations. If propagation of a covered
|
||||
work results from an entity transaction, each party to that
|
||||
transaction who receives a copy of the work also receives whatever
|
||||
licenses to the work the party's predecessor in interest had or could
|
||||
give under the previous paragraph, plus a right to possession of the
|
||||
Corresponding Source of the work from the predecessor in interest, if
|
||||
the predecessor has it or can get it with reasonable efforts.
|
||||
|
||||
You may not impose any further restrictions on the exercise of the
|
||||
rights granted or affirmed under this License. For example, you may
|
||||
not impose a license fee, royalty, or other charge for exercise of
|
||||
rights granted under this License, and you may not initiate litigation
|
||||
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||
any patent claim is infringed by making, using, selling, offering for
|
||||
sale, or importing the Program or any portion of it.
|
||||
|
||||
11. Patents.
|
||||
|
||||
A "contributor" is a copyright holder who authorizes use under this
|
||||
License of the Program or a work on which the Program is based. The
|
||||
work thus licensed is called the contributor's "contributor version".
|
||||
|
||||
A contributor's "essential patent claims" are all patent claims
|
||||
owned or controlled by the contributor, whether already acquired or
|
||||
hereafter acquired, that would be infringed by some manner, permitted
|
||||
by this License, of making, using, or selling its contributor version,
|
||||
but do not include claims that would be infringed only as a
|
||||
consequence of further modification of the contributor version. For
|
||||
purposes of this definition, "control" includes the right to grant
|
||||
patent sublicenses in a manner consistent with the requirements of
|
||||
this License.
|
||||
|
||||
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||
patent license under the contributor's essential patent claims, to
|
||||
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||
propagate the contents of its contributor version.
|
||||
|
||||
In the following three paragraphs, a "patent license" is any express
|
||||
agreement or commitment, however denominated, not to enforce a patent
|
||||
(such as an express permission to practice a patent or covenant not to
|
||||
sue for patent infringement). To "grant" such a patent license to a
|
||||
party means to make such an agreement or commitment not to enforce a
|
||||
patent against the party.
|
||||
|
||||
If you convey a covered work, knowingly relying on a patent license,
|
||||
and the Corresponding Source of the work is not available for anyone
|
||||
to copy, free of charge and under the terms of this License, through a
|
||||
publicly available network server or other readily accessible means,
|
||||
then you must either (1) cause the Corresponding Source to be so
|
||||
available, or (2) arrange to deprive yourself of the benefit of the
|
||||
patent license for this particular work, or (3) arrange, in a manner
|
||||
consistent with the requirements of this License, to extend the patent
|
||||
license to downstream recipients. "Knowingly relying" means you have
|
||||
actual knowledge that, but for the patent license, your conveying the
|
||||
covered work in a country, or your recipient's use of the covered work
|
||||
in a country, would infringe one or more identifiable patents in that
|
||||
country that you have reason to believe are valid.
|
||||
|
||||
If, pursuant to or in connection with a single transaction or
|
||||
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||
covered work, and grant a patent license to some of the parties
|
||||
receiving the covered work authorizing them to use, propagate, modify
|
||||
or convey a specific copy of the covered work, then the patent license
|
||||
you grant is automatically extended to all recipients of the covered
|
||||
work and works based on it.
|
||||
|
||||
A patent license is "discriminatory" if it does not include within
|
||||
the scope of its coverage, prohibits the exercise of, or is
|
||||
conditioned on the non-exercise of one or more of the rights that are
|
||||
specifically granted under this License. You may not convey a covered
|
||||
work if you are a party to an arrangement with a third party that is
|
||||
in the business of distributing software, under which you make payment
|
||||
to the third party based on the extent of your activity of conveying
|
||||
the work, and under which the third party grants, to any of the
|
||||
parties who would receive the covered work from you, a discriminatory
|
||||
patent license (a) in connection with copies of the covered work
|
||||
conveyed by you (or copies made from those copies), or (b) primarily
|
||||
for and in connection with specific products or compilations that
|
||||
contain the covered work, unless you entered into that arrangement,
|
||||
or that patent license was granted, prior to 28 March 2007.
|
||||
|
||||
Nothing in this License shall be construed as excluding or limiting
|
||||
any implied license or other defenses to infringement that may
|
||||
otherwise be available to you under applicable patent law.
|
||||
|
||||
12. No Surrender of Others' Freedom.
|
||||
|
||||
If conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot convey a
|
||||
covered work so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you may
|
||||
not convey it at all. For example, if you agree to terms that obligate you
|
||||
to collect a royalty for further conveying from those to whom you convey
|
||||
the Program, the only way you could satisfy both those terms and this
|
||||
License would be to refrain entirely from conveying the Program.
|
||||
|
||||
13. Remote Network Interaction; Use with the GNU General Public License.
|
||||
|
||||
Notwithstanding any other provision of this License, if you modify the
|
||||
Program, your modified version must prominently offer all users
|
||||
interacting with it remotely through a computer network (if your version
|
||||
supports such interaction) an opportunity to receive the Corresponding
|
||||
Source of your version by providing access to the Corresponding Source
|
||||
from a network server at no charge, through some standard or customary
|
||||
means of facilitating copying of software. This Corresponding Source
|
||||
shall include the Corresponding Source for any work covered by version 3
|
||||
of the GNU General Public License that is incorporated pursuant to the
|
||||
following paragraph.
|
||||
|
||||
Notwithstanding any other provision of this License, you have
|
||||
permission to link or combine any covered work with a work licensed
|
||||
under version 3 of the GNU General Public License into a single
|
||||
combined work, and to convey the resulting work. The terms of this
|
||||
License will continue to apply to the part which is the covered work,
|
||||
but the work with which it is combined will remain governed by version
|
||||
3 of the GNU General Public License.
|
||||
|
||||
14. Revised Versions of this License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions of
|
||||
the GNU Affero General Public License from time to time. Such new versions
|
||||
will be similar in spirit to the present version, but may differ in detail to
|
||||
address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the
|
||||
Program specifies that a certain numbered version of the GNU Affero General
|
||||
Public License "or any later version" applies to it, you have the
|
||||
option of following the terms and conditions either of that numbered
|
||||
version or of any later version published by the Free Software
|
||||
Foundation. If the Program does not specify a version number of the
|
||||
GNU Affero General Public License, you may choose any version ever published
|
||||
by the Free Software Foundation.
|
||||
|
||||
If the Program specifies that a proxy can decide which future
|
||||
versions of the GNU Affero General Public License can be used, that proxy's
|
||||
public statement of acceptance of a version permanently authorizes you
|
||||
to choose that version for the Program.
|
||||
|
||||
Later license versions may give you additional or different
|
||||
permissions. However, no additional obligations are imposed on any
|
||||
author or copyright holder as a result of your choosing to follow a
|
||||
later version.
|
||||
|
||||
15. Disclaimer of Warranty.
|
||||
|
||||
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
|
||||
16. Limitation of Liability.
|
||||
|
||||
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||
SUCH DAMAGES.
|
||||
|
||||
17. Interpretation of Sections 15 and 16.
|
||||
|
||||
If the disclaimer of warranty and limitation of liability provided
|
||||
above cannot be given local legal effect according to their terms,
|
||||
reviewing courts shall apply local law that most closely approximates
|
||||
an absolute waiver of all civil liability in connection with the
|
||||
Program, unless a warranty or assumption of liability accompanies a
|
||||
copy of the Program in return for a fee.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
How to Apply These Terms to Your New Programs
|
||||
|
||||
If you develop a new program, and you want it to be of the greatest
|
||||
possible use to the public, the best way to achieve this is to make it
|
||||
free software which everyone can redistribute and change under these terms.
|
||||
|
||||
To do so, attach the following notices to the program. It is safest
|
||||
to attach them to the start of each source file to most effectively
|
||||
state the exclusion of warranty; and each file should have at least
|
||||
the "copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
<one line to give the program's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If your software can interact with users remotely through a computer
|
||||
network, you should also make sure that it provides a way for users to
|
||||
get its source. For example, if your program is a web application, its
|
||||
interface could display a "Source" link that leads users to an archive
|
||||
of the code. There are many ways you could offer source, and different
|
||||
solutions will be better for different programs; see section 13 for the
|
||||
specific requirements.
|
||||
|
||||
You should also get your employer (if you work as a programmer) or school,
|
||||
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||
For more information on this, and how to apply and follow the GNU AGPL, see
|
||||
<http://www.gnu.org/licenses/>.
|
||||
@@ -0,0 +1,44 @@
|
||||
Runway — additional permission for plugins
|
||||
(an additional permission under section 7 of the GNU Affero General Public License, version 3)
|
||||
|
||||
Copyright (C) 2026 Quest ICT SAS de CV
|
||||
|
||||
Runway is free software: you can redistribute it and/or modify it under the terms of the
|
||||
GNU Affero General Public License as published by the Free Software Foundation, version 3
|
||||
(the file LICENSE), with the additional permission below. Runway is distributed in the hope
|
||||
that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public
|
||||
License for more details.
|
||||
|
||||
1. Definitions
|
||||
|
||||
"Runway" means the Runway kernel and every Runway plugin whose source carries this file.
|
||||
|
||||
"Published SPI" means the public classes and interfaces of the runway-spi artifact
|
||||
(the package mx.quest.runway.spi and its subpackages), together with the public classes
|
||||
and interfaces of any package named "spi" that a part of Runway publishes for other
|
||||
plugins to use (for example mx.quest.search.spi).
|
||||
|
||||
"Plugin" means an independent module that Runway loads as a plugin, that interacts with
|
||||
Runway only through the Published SPI, and that is not based on any part of Runway other
|
||||
than the Published SPI.
|
||||
|
||||
2. Permission
|
||||
|
||||
As an additional permission, the copyright holder gives you permission to combine Runway
|
||||
with Plugins, and to convey and run the resulting combination, without the terms of the
|
||||
GNU Affero General Public License applying to those Plugins. You may license, convey and
|
||||
run your Plugins under terms of your choice, provided that you continue to meet the terms
|
||||
of the GNU Affero General Public License for Runway itself, including offering the
|
||||
Corresponding Source of Runway, and of any modification you make to it, as that license
|
||||
requires.
|
||||
|
||||
3. Testing
|
||||
|
||||
Compiling a Plugin's tests against the runway-spi-testkit artifact, and running them, does
|
||||
not by itself make the Plugin subject to the GNU Affero General Public License.
|
||||
|
||||
4. Modified versions
|
||||
|
||||
If you modify Runway, you may extend this additional permission to your version, but you
|
||||
are not obliged to do so. If you do not wish to, delete this file from your version.
|
||||
@@ -0,0 +1,92 @@
|
||||
# Runway Search — Lucene engine
|
||||
|
||||
A Lucene-backed `SiteSearchEngine` for the [`search`](../search) plugin: a full-text index over the search
|
||||
plugin's `SearchCorpus` — every published page and content-source item the site has not excluded
|
||||
from search — each item's
|
||||
**title, description and body** with **per-locale stemming analysis**, a **tiered constant-score** relevance
|
||||
model (exact phrase → near phrase → all terms → any term), **fuzzy** (typo-tolerant) matching, and query-focused
|
||||
`<mark>` highlighting. Install it alongside `search` and it **transparently upgrades** the search box + `/search`
|
||||
results page — no change to that query surface.
|
||||
|
||||
- **Plugin id:** `search-lucene` (v`3.3.0`) — install folder `external/plugins/search-lucene/`
|
||||
- **Requires:** a Runway kernel with SPI `1.0.0` or later (`requiresSpi: ">=1.0.0"`, a floor every `1.x` kernel meets), `search >= 2.2.0` **and**
|
||||
`lucene-provider == 10.4.0`. With search 2.1.x, keep 3.1.0; with search 2.0.0, keep 3.0.0.
|
||||
- **Links:** only the Runway SPI (`mx.quest.runway.spi`) and the search SPI (`mx.quest.search.spi`)
|
||||
- **Java package:** `mx.quest.searchlucene` · **Lucene:** supplied by the [`lucene-provider`](../lucene-provider)
|
||||
plugin (compiled `provided`, **not** bundled here)
|
||||
|
||||
## Why a separate plugin
|
||||
|
||||
`search` splits search into a **query surface** (box + `/search`) and a swappable **engine** (`SiteSearchEngine`).
|
||||
The built-in engine matches with plain substrings; this one indexes with Lucene analysis and
|
||||
ranks by relevance, registering at a higher `priority()` so it wins wherever installed. It indexes the same
|
||||
`SearchCorpus` the built-in engine does — so the `search` plugin's per-site **`exclude`** list applies without this
|
||||
plugin reading it — drops a site's index the moment the kernel announces a change (a `SiteEventListener`), and
|
||||
implements the SPI's manual **reindex** hook so the operator's rebuild-index button rebuilds this index too. Lucene itself
|
||||
lives in the shared [`lucene-provider`](../lucene-provider) plugin (one copy deployment-wide). See
|
||||
[`docs/SEARCH-LUCENE-PLUGIN.md`](docs/SEARCH-LUCENE-PLUGIN.md) and [`CHANGELOG.md`](CHANGELOG.md).
|
||||
|
||||
## Tuning (per-site `siteSettings:`)
|
||||
|
||||
`fuzzy`, `fuzzyBoost`, `titleBoost`, `descriptionBoost`, and the four tier scores (`tierPhraseTitle`,
|
||||
`tierPhraseBody`, `tierNearPhrase`, `tierAllTerms`). App-level `settings:` choose index `storage` (heap/disk) and
|
||||
the disk `indexRoot`. Defaults reproduce the historical ranking, so an unconfigured site behaves as before.
|
||||
|
||||
## Build
|
||||
|
||||
```bash
|
||||
export JAVA_HOME=/path/to/jdk-25
|
||||
(cd ../search && mvn -DskipTests install) # the jar this compiles against, into ~/.m2
|
||||
mvn verify # 72 unit tests + the package
|
||||
# → target/runway-plugin-search-lucene.jar (thin jar — NO bundled Lucene)
|
||||
# target/search-lucene/ (folder — cp -r into <external>/plugins/ + restart)
|
||||
# target/runway-plugin-search-lucene-3.3.0.zip (upload at /__app/plugins → install)
|
||||
JAVA_HOME=/path/to/jdk-25 HOST_JAR=/path/to/runway-app-<ver>-exec.jar VERIFY_TMPDIR=/some/scratch scripts/verify-against-host.sh
|
||||
```
|
||||
|
||||
The build compiles against the search plugin, `provided` from `~/.m2`: install it first with
|
||||
`mvn -DskipTests install` in `../search` (the verify script does). The first build downloads its Maven dependencies,
|
||||
and needs the `runway-spi` jars installed in `~/.m2` as the
|
||||
[authoring guide §2](../docs/PLUGIN-AUTHORING-GUIDE.md#2-prerequisites) describes. This plugin itself is never installed. At runtime the deployment must also carry the `search` plugin (2.2.0 or later) **and**
|
||||
the `lucene-provider` plugin (the Lucene binaries): drop all three folders into `external/plugins/`.
|
||||
|
||||
## Log messages you can ignore
|
||||
|
||||
### `Java vector incubator module is not readable`
|
||||
|
||||
Once per start of the host, the first time Lucene is used (usually the first search, on a request thread), the log
|
||||
shows:
|
||||
|
||||
```
|
||||
WARN … o.a.l.i.v.VectorizationProvider : Java vector incubator module is not readable. For optimal vector performance, pass '--add-modules jdk.incubator.vector' to enable Vector API.
|
||||
```
|
||||
|
||||
Lucene prints it (the library the `lucene-provider` plugin supplies). Nothing is wrong. **Leave it off**, for three
|
||||
reasons.
|
||||
|
||||
- The flag makes Lucene's vector maths faster. Lucene needs that mainly for k-nearest-neighbour *vector* search.
|
||||
Runway's search is keyword search (terms, phrases, typo-tolerant matches) and uses no vectors.
|
||||
- A site's index is small (its published pages and items), so there is no time to win.
|
||||
- `jdk.incubator.vector` is an *incubator* module, a JDK API that is not final. With it, the JVM prints
|
||||
`WARNING: Using incubator modules: jdk.incubator.vector` at every start, and a later JDK may change or drop the
|
||||
module.
|
||||
|
||||
If you want it anyway, add `--add-modules jdk.incubator.vector` to `JAVA_OPTS` in a systemd **drop-in** under
|
||||
`/etc/systemd/system/runway.service.d/`. Never edit the main unit, `runway.service`: the installer rewrites it at
|
||||
every upgrade. `Environment=` sets the whole variable, so the line must also carry your heap flags:
|
||||
|
||||
```ini
|
||||
# /etc/systemd/system/runway.service.d/20-heap.conf
|
||||
[Service]
|
||||
Environment="JAVA_OPTS=-Xms256m -Xmx1g --add-modules jdk.incubator.vector"
|
||||
```
|
||||
|
||||
Then run `sudo systemctl daemon-reload && sudo systemctl restart runway`. The installer's `--heap` rewrites
|
||||
`20-heap.conf` whole and drops the flag, so add it again after each `--heap`. Runway's administration manual
|
||||
(§15, *Memory tuning*) explains the drop-ins.
|
||||
|
||||
## License
|
||||
|
||||
GNU Affero General Public License v3.0 with an additional permission for plugins (`LICENSE`, `LICENSE-EXCEPTION`),
|
||||
copyright Quest ICT SAS de CV. The permission means that a plugin which uses only the published SPI, including
|
||||
search's own SPI for engines, may carry any license.
|
||||
@@ -0,0 +1,224 @@
|
||||
# Runway Search — Lucene engine — design & reference
|
||||
|
||||
> The companion engine for the `../search` plugin, and the workspace's reference for **two** hard-to-get-right
|
||||
> plugin patterns at once: implementing another plugin's **published SPI** (`requires:`), and **consuming a
|
||||
> shared library-provider plugin** (`../lucene-provider`) instead of bundling the library privately. Grounded in
|
||||
> the Runway kernel as built. Since 3.0.0 it links **only the Runway SPI and the search plugin's SPI**.
|
||||
|
||||
## 1. What it does
|
||||
|
||||
Implements `search`'s `SiteSearchEngine` SPI with Apache Lucene. Where the built-in engine substring-matches,
|
||||
this one builds a full-text index over each searchable item's **title**, **description**, and **body text**
|
||||
(extracted from the item's indexable material via `HtmlText`), analyzes queries with a **per-locale stemming
|
||||
analyzer**, and ranks with a **tiered constant-score** model layered on Lucene's BM25. It registers at
|
||||
`priority()` 100, so the shared search box and the results page transparently use it wherever it is installed —
|
||||
and fall back to the built-in engine if this plugin is removed.
|
||||
|
||||
What it indexes is the search plugin's **`SearchCorpus`** (search 2.0.0): every published page and content-source
|
||||
item of the kernel's listing **minus the site's search exclusions**. The built-in engine builds from the same
|
||||
corpus, so which items are searchable never depends on which engine serves the query, and the `exclude` rule lives
|
||||
in exactly one place — this plugin never reads the search plugin's settings.
|
||||
|
||||
## 2. The two `requires:` gates and the SPI floor
|
||||
|
||||
`plugin.yml` declares `requires: [ "search >= 2.2.0", "lucene-provider == 10.4.0" ]` and `requiresSpi: ">=1.0.0"`:
|
||||
|
||||
- **`search >= 2.2.0`** publishes the `SiteSearchEngine` interface this plugin implements and the `SearchCorpus` it
|
||||
indexes (both in `mx.quest.search.spi`). This plugin compiles against the search plugin as a `provided`
|
||||
dependency from `~/.m2` (installed from `../search`; never bundled). Both plugin jars load into ONE shared classloader, so the SPI types have a single `Class` identity and
|
||||
Spring collects this engine into `search`'s `List<SiteSearchEngine>`. `>=` (not exact) because the search SPI is
|
||||
API-stable — it grows by `default` methods and kept constructors only; **2.2.0** is the floor (since 3.2.0)
|
||||
because this plugin keeps one index per language, which a visitor reaches only when the search box on a
|
||||
localized page submits to the results page in that language — search 2.2.0 does that, while 2.1.x always
|
||||
submitted to the default-language results page. (3.1.x needed 2.1.0, the first with the `SearchHit`
|
||||
constructor that carries the matched words; 2.0.0 was the first to publish `SearchCorpus`.) Only the `spi` package is a contract: a build-time test fails if this plugin links any
|
||||
other search class.
|
||||
- **`lucene-provider == 10.4.0`** is the standalone code-less provider (`../lucene-provider`) that places the
|
||||
single deployment-wide copy of Lucene on the shared classloader. **`==` (exact)** because this plugin is
|
||||
**compiled against the 10.4.0 binaries** — a different Lucene could be binary-incompatible.
|
||||
- **`requiresSpi: ">=1.0.0"`** — the frozen 1.x contract, which carries the services it uses: `PluginSettings`
|
||||
(0.4.0), `Sites` (0.5.0), `SiteEventListener` and `CatalogEntry` (0.6.0).
|
||||
|
||||
If a gate is unsatisfied (missing/disabled/wrong version, or an older kernel), the host **does not load** this
|
||||
plugin (skipped with a reason, shown "Blocked" in the console) — so the SPI types AND every Lucene class are
|
||||
guaranteed present when this plugin's beans wire.
|
||||
|
||||
## 2a. What it uses, and nothing else
|
||||
|
||||
| Need | Published service |
|
||||
|------|-------------------|
|
||||
| what to index, its indexable text, the manual refresh | `SearchCorpus.corpus` / `indexableText` / `refresh` (search) |
|
||||
| a site's default locale (the analyzer) | `Sites.find` (kernel SPI) |
|
||||
| the per-site ranking knobs | `PluginSettings.site` (kernel SPI; descriptor defaults applied under the stored values) |
|
||||
| drop an index when content changes | `SiteEventListener.onCatalogChanged` (kernel SPI; one `CONSUMER` listener) |
|
||||
| app-level storage settings | its own `@ConfigurationProperties` bean under `runway.plugin.search-lucene` |
|
||||
|
||||
Beans: `searchLuceneStorageProps`, `searchLuceneEngine`, `searchLuceneSiteEvents`, `searchLuceneAdminModel` — every
|
||||
name starts with the plugin id in lowerCamelCase (the kernel's rule for the bean namespace plugins share).
|
||||
`SearchLuceneConfigTest` scans the compiled classes' constant pools: nothing of `mx.quest.runway` outside `.spi`,
|
||||
nothing of `mx.quest.search` outside `.spi`, no Caffeine.
|
||||
|
||||
## 3. Graduated from private bundling to the provider
|
||||
|
||||
search-lucene **used to** bundle Lucene privately in its own `lib/` (it was the only consumer). Lucene has
|
||||
**graduated** to the standalone `lucene-provider` (whose version IS the Lucene version):
|
||||
|
||||
- `pom.xml` now marks `lucene-core` + `lucene-analysis-common` + `lucene-highlighter` (and their transitives
|
||||
`lucene-memory` + `lucene-queries`) as **`provided`** — compile-only, supplied by the provider at runtime.
|
||||
- **Nothing** is copied into this plugin's own `lib/`. The staged install folder is the thin jar + templates +
|
||||
i18n only; a `clean package` verifies no Lucene jar appears in `target/search-lucene/`.
|
||||
- The search jar is compile-only too (never bundled — a second `Class` identity would break by-type SPI
|
||||
collection).
|
||||
|
||||
One Lucene version deployment-wide; no silent classpath clash. On a Lucene upgrade, bump `../lucene-provider` and
|
||||
this plugin's `${lucene.version}` + `requires:` pin together, then re-cut.
|
||||
|
||||
## 4. Ranking model
|
||||
|
||||
`buildQuery` composes a **tiered, additive constant-score** query — the tiers are `SHOULD` clauses, so a hit
|
||||
scores the **sum** of the tiers it satisfies, giving a deterministic ordering:
|
||||
|
||||
| Tier | What it matches | Score |
|
||||
|------|-----------------|-------|
|
||||
| any-terms | each term across title (× `titleBoost`), description (× `descriptionBoost`), body; **+ fuzzy** clauses when `fuzzy` is on | BM25 (× boosts) — the base layer that separates hits *within* a tier |
|
||||
| near phrase (body) | the query as a body `PhraseQuery` with slop 1 (lightly reordered / 1 gap) | constant `tierNearPhrase` |
|
||||
| exact phrase (body) | the query as an exact (slop 0) body phrase | constant `tierPhraseBody` |
|
||||
| exact phrase (title) | the query as an exact title phrase | constant `tierPhraseTitle` |
|
||||
| all-terms-anywhere | every term appears in some field (`MUST` across fields) | constant `tierAllTerms` |
|
||||
|
||||
Defaults reproduce the historical ranking constants (`tierPhraseTitle 4000 > tierPhraseBody 2000 > tierNearPhrase
|
||||
800 > tierAllTerms 300`; `titleBoost 8`, `descriptionBoost 4`; `fuzzy` on, `fuzzyBoost 0.4`). The phrase tiers
|
||||
are skipped for a single-term query (a lone term IS its own phrase — no double-count).
|
||||
|
||||
- **Fuzzy** (`FuzzyQuery`): typo tolerance with a length-aware edit budget (`maxEdits`: 0 for ≤2 chars, 1 for
|
||||
≤5, 2 beyond), fixed 1-char prefix, transpositions on. Fuzzy operates on the **analyzed (stemmed)** term.
|
||||
- **Per-locale analyzers** (`LocaleAnalyzers`): a Lucene language `Analyzer` (with that language's stopwords +
|
||||
stemmer) chosen by the **site's default locale** where one exists (en, es, fr, de, it, pt, ru, …), else
|
||||
`StandardAnalyzer`. The **same** analyzer is used at index and query time — stemming is analysis-time, so the
|
||||
two must never drift (or a stemmed query term would never match a stemmed indexed term).
|
||||
- **Highlighting** (`UnifiedHighlighter` + `DefaultPassageFormatter`): a query-focused body passage with hits
|
||||
wrapped in `<mark>…</mark>`. Private control-char markers are used internally; the passage is **HTML-escaped
|
||||
first, THEN** the markers become real `<mark>` tags — so page content can't inject markup while the highlight
|
||||
tags survive. Falls back to the description / a leading body slice when there is no highlightable passage.
|
||||
This is the `SearchHit` snippet contract (escape everything, wrap only hits in `<mark>`), and the search surface
|
||||
renders the snippet as raw HTML on that basis.
|
||||
- **Matched words** (since 3.1.0, `MatchedForms`): each returned hit also carries `SearchHit.terms`, the words the
|
||||
query matched **as the page writes them**, which search 2.1.0 hands to the page the result opens for
|
||||
highlighting. The stored title, description and body go through the same analyzer; a token whose term is a query
|
||||
term (or, with `fuzzy` on, within the fuzzy edit distance, same rule as the clauses) is kept as the text its
|
||||
offsets cover. So `maestría` (term `maestr`) reports `maestrías` from the page. At most 20 words; the first
|
||||
64 KiB of each text are read, so a long page costs a fixed amount per hit. Stop words match nothing and are never
|
||||
reported.
|
||||
|
||||
## 5. Index lifecycle & storage
|
||||
|
||||
- **Source:** `SearchCorpus.corpus(siteId)` — every published item minus the site's exclusions — and
|
||||
`SearchCorpus.indexableText(siteId, entry, locale)` for its body material (stripped to text) — the page
|
||||
as rendered in that language, so strings from the site's bundles are in it.
|
||||
- **One index per language (since 3.2.0).** Each item is indexed once per language it exists in: title,
|
||||
description, body in that language, and the hit's URL `CatalogEntry.pathFor(locale)` — its real address there.
|
||||
A site has one index per language it speaks, analyzed with **that language's analyzer**: the language's own
|
||||
documents plus, for an item that does not exist in it, the item's **primary-locale** document (the site default
|
||||
when the item has it, else its own first language), so a page published in one language only is still found
|
||||
from every other. A query searches its own language's index (`SearchQuery.locale()` — the results page's
|
||||
language, or the API's `?lang=`) with that analyzer; a language the site does not speak searches the site
|
||||
default's. A fallback document is analyzed with the index's analyzer, not its own language's, so it matches on
|
||||
exact and lightly stemmed forms rather than every inflection. Before 3.2.0 a site had one index of
|
||||
primary-locale documents with the default language's analyzer, so every language searched default-language
|
||||
text. The console's count is of items, not per-language documents.
|
||||
- **Store (app-level `settings:`, `LuceneStorageProps`, restart-only — a PLATFORM concern, not per-site, because
|
||||
a tenant-editable path is an isolation/abuse risk):**
|
||||
- `heap` (default) — an in-memory `ByteBuffersDirectory` per language; rebuilt on first use after boot.
|
||||
- `disk` — a memory-mapped `MMapDirectory` per language under `indexRoot/<siteId>/<language>` (since 3.2.0;
|
||||
the site id and the language are validated and the resolved path is asserted to stay under the normalized
|
||||
index root — traversal-safe). The index files a 3.1.x build left directly under `indexRoot/<siteId>` are
|
||||
deleted on the first rebuild — only files Lucene names (`segments*`, `write.lock`, codec files `_*.*`), once
|
||||
per site per process, so a misdirected `indexRoot` loses nothing else.
|
||||
- **Freshness:** each index is **cached per site** and dropped by the plugin's `SiteEventListener`
|
||||
(`LuceneSiteEvents`, phase `CONSUMER`) on **every** catalog change of the site — a page write, a content source's
|
||||
change, a site lifecycle event, any plugin's settings save (the search plugin's `exclude` list and a source's
|
||||
own settings both reshape the corpus). The kernel delivers it after its own caches are evicted and after every
|
||||
content source has dropped its state, so the next query rebuilds from the new content. A build that a change
|
||||
overtook (it may have read the old corpus) is kept as already stale: it answers the query that built it, and the
|
||||
next query rebuilds. A 30 s TTL remains as the backstop for changes no event announces, and the SPI's
|
||||
`reindex(siteId)` hook (the operator's rebuild-index button) refreshes the kernel's listing through
|
||||
`SearchCorpus.refresh`, then drops and rebuilds eagerly, returning the fresh document count. The build is
|
||||
rebuild-from-scratch (`deleteAll` then re-add), so a disk index is never left stale.
|
||||
- **Safety:** `search(...)` **never throws** — a Lucene/store/corpus failure logs and returns no results, so the
|
||||
query surface degrades to "no results", never a 500. Every surface is scoped to the queried `siteId`.
|
||||
- **No personal data.** The index is derived from published content and lives in heap or under `indexRoot`, not in
|
||||
the site folder; the plugin declares no `siteData.personal`.
|
||||
|
||||
## 6. Console & settings
|
||||
|
||||
- **App-level** `settings:` — `storage` (enum heap/disk) + `indexRoot` (string). Superadmin-only; applied on
|
||||
restart.
|
||||
- **Per-tenant** `siteSettings:` — the 8 ranking knobs (`fuzzy`, `fuzzyBoost`, `titleBoost`, `descriptionBoost`,
|
||||
`tierPhraseTitle`, `tierPhraseBody`, `tierNearPhrase`, `tierAllTerms`), read per query (a save applies to the
|
||||
next query) through `PluginSettings`. The editor is gated by the `settings` control point. `decimal` ignores `range`
|
||||
(authoring guide §4.1), so `RankingConfig` defaults + clamps every value defensively.
|
||||
- A dashboard card + admin fragment (bean `searchLuceneAdminModel`) show the active engine key, the site's indexed
|
||||
item count, the storage mode, and the effective title boost.
|
||||
|
||||
## 7. Verify
|
||||
|
||||
- **Offline unit tests** (`mvn verify`, 72 tests, on the `runway-spi-testkit` fakes and search's own
|
||||
`SiteSearchCorpus`): SPI contract (never-throws, empty index, unsafe/unknown site, limit, tie order), the search
|
||||
plugin's exclusions reaching the index through its corpus, the primary-locale title/body/URL, one index per
|
||||
language (`LucenePerLanguageTest`: each language's own text, analyzer and address, the primary-locale fallback,
|
||||
an unknown language, the item count, the per-language disk folders, only Lucene-named 3.1.x files deleted, a
|
||||
search from inside the site's own build answering nothing), `reindex`
|
||||
(listing refresh + immediate rebuild inside the TTL), the listener dropping the index for every cause (page,
|
||||
content, settings of another plugin, lifecycle, a replayed change) and only for its site, the mid-build change,
|
||||
tiering (exact phrase > scattered; title phrase > body phrase; the documented tier sum), fuzzy on/off applied on
|
||||
the next query, per-locale stemming (English `running`↔`run`; Spanish `producto`↔`productos`; unknown locale →
|
||||
StandardAnalyzer), heap and disk answering identically, `<mark>` highlighting (incl. page-markup escaping), each
|
||||
tuning knob, defensive config parsing, and the contract test (wiring from published services only, bean names,
|
||||
template bean references, descriptor floors and version, code fallbacks = descriptor defaults, i18n, the
|
||||
constant-pool scan).
|
||||
- **Live** (`scripts/verify-against-host.sh`; honours `HOST_JAR`, `VERIFY_TMPDIR`, `VERIFY_LOG_DIR`; packages
|
||||
everything offline and never `mvn install`s): boots the packaged host twice on the same fixture site — first
|
||||
search 2.0.0 + search-lucene 3.0.0 (built from git at `BASELINE_REF`, a commit carrying those two versions; when
|
||||
`BASELINE_REF` is unset, the default, or `SKIP_BASELINE=1`, the script prints a note and runs only the checks on the
|
||||
current pair), then the current search + this release with the index on disk — and asserts that twelve queries
|
||||
answer **byte-identically** (order, URLs, titles, snippets, scores) once the `link` and `terms` fields 3.0.0 never had are set aside; those it checks on
|
||||
their own: each hit carries its marked link and at least every word its snippet marks. (Until 3.1.0 the baseline
|
||||
was 2.2.1, which a Runway 1.0 kernel blocks for linking kernel internals; 3.0.0 had matched it byte for byte.) On
|
||||
the current pair it asserts `3 registered, 0 blocked` with zero host-linkage and bean-name/surface warnings, the
|
||||
console card and admin fragment, a save of search's `exclude` list and of this plugin's knobs reaching the next
|
||||
query without a reindex, and the rebuild-index POST reporting this engine's count.
|
||||
|
||||
## 8. Log messages you can ignore
|
||||
|
||||
### `Java vector incubator module is not readable`
|
||||
|
||||
Once per start of the host, the first time Lucene is used (usually the first search, on a request thread), the log
|
||||
shows:
|
||||
|
||||
```
|
||||
WARN … o.a.l.i.v.VectorizationProvider : Java vector incubator module is not readable. For optimal vector performance, pass '--add-modules jdk.incubator.vector' to enable Vector API.
|
||||
```
|
||||
|
||||
Lucene prints it (the library the `lucene-provider` plugin supplies). Nothing is wrong. **Leave it off**, for three
|
||||
reasons.
|
||||
|
||||
- The flag makes Lucene's vector maths faster. Lucene needs that mainly for k-nearest-neighbour *vector* search.
|
||||
Runway's search is keyword search (terms, phrases, typo-tolerant matches) and uses no vectors.
|
||||
- A site's index is small (its published pages and items), so there is no time to win.
|
||||
- `jdk.incubator.vector` is an *incubator* module, a JDK API that is not final. With it, the JVM prints
|
||||
`WARNING: Using incubator modules: jdk.incubator.vector` at every start, and a later JDK may change or drop the
|
||||
module.
|
||||
|
||||
If you want it anyway, add `--add-modules jdk.incubator.vector` to `JAVA_OPTS` in a systemd **drop-in** under
|
||||
`/etc/systemd/system/runway.service.d/`. Never edit the main unit, `runway.service`: the installer rewrites it at
|
||||
every upgrade. `Environment=` sets the whole variable, so the line must also carry your heap flags:
|
||||
|
||||
```ini
|
||||
# /etc/systemd/system/runway.service.d/20-heap.conf
|
||||
[Service]
|
||||
Environment="JAVA_OPTS=-Xms256m -Xmx1g --add-modules jdk.incubator.vector"
|
||||
```
|
||||
|
||||
Then run `sudo systemctl daemon-reload && sudo systemctl restart runway`. The installer's `--heap` rewrites
|
||||
`20-heap.conf` whole and drops the flag, so add it again after each `--heap`. Runway's administration manual
|
||||
(§15, *Memory tuning*) explains the drop-ins.
|
||||
@@ -0,0 +1,30 @@
|
||||
# Runway Search — Lucene engine — English strings.
|
||||
|
||||
# Grantable permission (permissions matrix label)
|
||||
searchlucene.perm.settings=Configure Lucene search
|
||||
|
||||
# App-level settings form labels (superadmin — platform storage)
|
||||
searchlucene.set.storage=Index storage
|
||||
searchlucene.set.indexRoot=Disk index root folder
|
||||
|
||||
# Per-tenant settings form labels (site ranking tuning)
|
||||
searchlucene.set.fuzzy=Typo-tolerant (fuzzy) matching
|
||||
searchlucene.set.fuzzyBoost=Fuzzy match weight
|
||||
searchlucene.set.titleBoost=Title match boost
|
||||
searchlucene.set.descriptionBoost=Description match boost
|
||||
searchlucene.set.tierPhraseTitle=Exact phrase in title — score
|
||||
searchlucene.set.tierPhraseBody=Exact phrase in body — score
|
||||
searchlucene.set.tierNearPhrase=Near phrase in body — score
|
||||
searchlucene.set.tierAllTerms=All terms present — score
|
||||
|
||||
# Dashboard card
|
||||
searchlucene.card.title=Lucene search index
|
||||
searchlucene.card.pages=indexed items
|
||||
|
||||
# Admin status fragment
|
||||
searchlucene.admin.title=Lucene index status
|
||||
searchlucene.admin.engine=Engine
|
||||
searchlucene.admin.pages=Indexed items
|
||||
searchlucene.admin.storage=Storage
|
||||
searchlucene.admin.boost=Title boost
|
||||
searchlucene.admin.note=This engine supersedes the built-in search whenever it is installed. It ranks results in tiers (exact phrase, near phrase, all terms, any term), tolerates typos, and stems per the site language. The index refreshes automatically as content changes; no manual rebuild is needed.
|
||||
@@ -0,0 +1,30 @@
|
||||
# Runway Search — motor Lucene — cadenas en español.
|
||||
|
||||
# Permiso otorgable (etiqueta de la matriz de permisos)
|
||||
searchlucene.perm.settings=Configurar búsqueda Lucene
|
||||
|
||||
# Etiquetas del formulario de configuración a nivel de aplicación (superadmin — almacenamiento)
|
||||
searchlucene.set.storage=Almacenamiento del índice
|
||||
searchlucene.set.indexRoot=Carpeta raíz del índice en disco
|
||||
|
||||
# Etiquetas del formulario de configuración por sitio (ajuste de relevancia)
|
||||
searchlucene.set.fuzzy=Coincidencia tolerante a errores (difusa)
|
||||
searchlucene.set.fuzzyBoost=Peso de coincidencia difusa
|
||||
searchlucene.set.titleBoost=Refuerzo de coincidencia en título
|
||||
searchlucene.set.descriptionBoost=Refuerzo de coincidencia en descripción
|
||||
searchlucene.set.tierPhraseTitle=Frase exacta en título — puntuación
|
||||
searchlucene.set.tierPhraseBody=Frase exacta en cuerpo — puntuación
|
||||
searchlucene.set.tierNearPhrase=Frase cercana en cuerpo — puntuación
|
||||
searchlucene.set.tierAllTerms=Todos los términos presentes — puntuación
|
||||
|
||||
# Tarjeta del panel
|
||||
searchlucene.card.title=Índice de búsqueda Lucene
|
||||
searchlucene.card.pages=elementos indexados
|
||||
|
||||
# Fragmento de estado (admin)
|
||||
searchlucene.admin.title=Estado del índice Lucene
|
||||
searchlucene.admin.engine=Motor
|
||||
searchlucene.admin.pages=Elementos indexados
|
||||
searchlucene.admin.storage=Almacenamiento
|
||||
searchlucene.admin.boost=Refuerzo de título
|
||||
searchlucene.admin.note=Este motor sustituye a la búsqueda integrada siempre que está instalado. Ordena los resultados por niveles (frase exacta, frase cercana, todos los términos, cualquier término), tolera erratas y lematiza según el idioma del sitio. El índice se actualiza automáticamente cuando cambian las páginas; no hace falta reconstruirlo a mano.
|
||||
@@ -0,0 +1,78 @@
|
||||
# =============================================================================
|
||||
# Runway Search — Lucene engine
|
||||
# A full-text SiteSearchEngine (title + description + body) with per-locale
|
||||
# analysis (stemming), a TIERED constant-score ranking (exact phrase → near
|
||||
# phrase → all-terms → any-terms), FUZZY matching, and query-focused <mark>
|
||||
# highlighting — a real upgrade over the built-in substring engine.
|
||||
#
|
||||
# Indexes the search plugin's SearchCorpus (the site's published pages and
|
||||
# content items minus the site's search exclusions — the same corpus the
|
||||
# built-in engine indexes), drops a site's index on every change the kernel
|
||||
# announces (a SiteEventListener), and implements the engine SPI's manual
|
||||
# reindex hook. Since 3.0.0 it links only the Runway SPI and the search SPI.
|
||||
#
|
||||
# Lucene lives in the standalone `lucene-provider` plugin: this plugin does not
|
||||
# bundle Lucene in its own lib/. It declares two hard dependencies:
|
||||
# - requires: search >= 2.2.0 — publishes SiteSearchEngine, SearchCorpus and SearchHit.terms
|
||||
# - requires: lucene-provider == 10.4.0 — the exact Lucene binaries it is compiled against
|
||||
#
|
||||
# The install folder name MUST equal this `id`: external/plugins/search-lucene/.
|
||||
# =============================================================================
|
||||
id: search-lucene
|
||||
name: Search — Lucene engine
|
||||
version: 3.3.0
|
||||
|
||||
# The @Configuration registered before refresh. Package mx.quest.searchlucene lives OUTSIDE mx.quest.runway.
|
||||
mainClass: mx.quest.searchlucene.SearchLuceneConfig
|
||||
|
||||
# HARD dependencies (both must be satisfied or this plugin is skipped with a reason, shown "Blocked" in the UI):
|
||||
# - search >= 2.1.0: publishes the SiteSearchEngine SPI this plugin implements and the SearchCorpus it indexes.
|
||||
# `>=` (not exact) because the search SPI is API-stable (it grows by default methods and kept constructors only);
|
||||
# 2.2.0 is the floor (3.2.0): this plugin keeps one index per language, which a visitor reaches only when the
|
||||
# search box on a localized page submits to the results page in that language — search 2.2.0 does that (2.1.x
|
||||
# always submitted to the default-language results page, so every query arrived in the default language).
|
||||
# Before 3.2.0 the floor was 2.1.0, the first search with the SearchHit constructor carrying the matched words.
|
||||
# - lucene-provider == 10.4.0: EXACT pin — this plugin is compiled against the 10.4.0 Lucene binaries the
|
||||
# provider ships; a different Lucene could be binary-incompatible, so `==` (not `>=`).
|
||||
requires: [ "search >= 2.2.0", "lucene-provider == 10.4.0" ]
|
||||
|
||||
# The lowest Runway SPI whose services this plugin uses (PluginSettings, Sites, SiteEventListener and the
|
||||
# CatalogEntry the corpus hands out). A kernel below SPI 1.0.0 BLOCKS this plugin at startup with a reason.
|
||||
requiresSpi: ">=1.0.0"
|
||||
|
||||
# --- Grantable control-point permission (gates the per-tenant tuning editor) -----------------------------
|
||||
permissions:
|
||||
- { id: settings, realm: tenant, label: searchlucene.perm.settings, defaultRoles: [] }
|
||||
|
||||
# --- App-level settings (superadmin): PLATFORM concerns only — WHERE the index bytes live. -----------------
|
||||
# A tenant-editable filesystem path would be an isolation/abuse risk, so storage is app-level, not per-site.
|
||||
# Applied on RESTART (bound by the plugin's own @ConfigurationProperties bean from
|
||||
# external/plugin-settings/search-lucene.yml).
|
||||
# storage : heap → in-memory ByteBuffersDirectory (default; no disk, rebuilt on boot)
|
||||
# disk → MMapDirectory under indexRoot/<siteId> (survives restart, memory-mapped)
|
||||
# indexRoot : the root folder for disk indexes (per-site subfolders created under it, traversal-guarded)
|
||||
settings:
|
||||
- { key: storage, type: enum, values: [heap, disk], default: heap, label: searchlucene.set.storage }
|
||||
- { key: indexRoot, type: string, default: "./external/plugins/search-lucene/index", label: searchlucene.set.indexRoot }
|
||||
|
||||
# --- Per-tenant settings (tenant-owned ranking tuning; over sites/<id>/plugins/search-lucene.yml) ----------
|
||||
# Applied IMMEDIATELY (read per query through the SPI's PluginSettings). `decimal` IGNORES range
|
||||
# (authoring guide §4.1), so the engine clamps every knob to a sane range itself. Defaults reproduce the
|
||||
# historical constants, so an unconfigured site ranks exactly as before this schema existed.
|
||||
siteSettings:
|
||||
# Fuzzy (typo-tolerant) matching — on/off + how much a fuzzy hit is worth relative to an exact term hit.
|
||||
- { key: fuzzy, type: boolean, default: true, label: searchlucene.set.fuzzy }
|
||||
- { key: fuzzyBoost, type: decimal, default: 0.4, label: searchlucene.set.fuzzyBoost }
|
||||
# Per-field term boosts (applied to the any-terms tier's term matches).
|
||||
- { key: titleBoost, type: decimal, default: 8.0, label: searchlucene.set.titleBoost }
|
||||
- { key: descriptionBoost, type: decimal, default: 4.0, label: searchlucene.set.descriptionBoost }
|
||||
# Tier scores — the constant score a document earns for matching each tier (bigger = stronger relevance
|
||||
# signal). exact-phrase-in-title ≫ exact-phrase-in-body ≫ near-phrase-in-body ≫ all-terms-anywhere.
|
||||
- { key: tierPhraseTitle, type: decimal, default: 4000, label: searchlucene.set.tierPhraseTitle }
|
||||
- { key: tierPhraseBody, type: decimal, default: 2000, label: searchlucene.set.tierPhraseBody }
|
||||
- { key: tierNearPhrase, type: decimal, default: 800, label: searchlucene.set.tierNearPhrase }
|
||||
- { key: tierAllTerms, type: decimal, default: 300, label: searchlucene.set.tierAllTerms }
|
||||
|
||||
# --- Tenant dashboard card (fragment resolves to __plugin__/search-lucene/dashboard) ----------------------
|
||||
dashboardCards:
|
||||
- { realm: tenant, order: 41, fragment: dashboard, permission: "search-lucene|settings" }
|
||||
@@ -0,0 +1,195 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
||||
<!--
|
||||
Inherit the SAME managed versions the Runway kernel uses (Spring Boot 4.0.6) so every `provided` Spring type
|
||||
is byte-identical at runtime. A plugin is NOT a Boot application — NO repackage; `mvn package` produces a THIN
|
||||
jar of only this plugin's classes.
|
||||
|
||||
SPI only (3.0.0): the plugin links nothing of the kernel but `runway-spi` (no runway-app, in any scope), and
|
||||
nothing of the search plugin but its published SPI package `mx.quest.search.spi` (SiteSearchEngine,
|
||||
SearchCorpus, SearchQuery, SearchHit). Lucene comes from the `lucene-provider` plugin (`provided` here,
|
||||
`requires: lucene-provider == 10.4.0` in plugin.yml), so this pom bundles NOTHING into a lib/ folder.
|
||||
-->
|
||||
<parent>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-parent</artifactId>
|
||||
<version>4.0.6</version>
|
||||
<relativePath/>
|
||||
</parent>
|
||||
|
||||
<groupId>mx.quest</groupId>
|
||||
<artifactId>runway-plugin-search-lucene</artifactId>
|
||||
<version>3.3.0</version>
|
||||
<packaging>jar</packaging>
|
||||
<name>Runway Search — Lucene engine</name>
|
||||
<licenses>
|
||||
<license>
|
||||
<name>GNU Affero General Public License v3.0, with the Runway additional permission for plugins</name>
|
||||
<url>https://www.gnu.org/licenses/agpl-3.0.txt</url>
|
||||
<distribution>repo</distribution>
|
||||
<comments>See LICENSE and LICENSE-EXCEPTION.</comments>
|
||||
</license>
|
||||
</licenses>
|
||||
<description>
|
||||
A Lucene-backed SiteSearchEngine for the Runway `search` plugin: a full-text index over each page's
|
||||
title, description and body with per-locale analysis (stemming) and a tiered constant-score ranking —
|
||||
exact phrase, near phrase, all-terms, any-terms — plus fuzzy matching and query-focused snippet
|
||||
highlighting. It indexes the search plugin's SearchCorpus, declares `requires: search >= 2.2.0` and
|
||||
`requires: lucene-provider == 10.4.0`, registers at a higher priority than the built-in engine, and
|
||||
transparently upgrades the search box and results page. Links only the Runway SPI and the search SPI;
|
||||
Lucene is supplied by the lucene-provider plugin (provided).
|
||||
</description>
|
||||
|
||||
<properties>
|
||||
<java.version>25</java.version>
|
||||
<maven.compiler.release>25</maven.compiler.release>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
<!-- Reproducible builds: pins every archive entry's timestamp so two builds of the same source
|
||||
produce byte-identical artifacts. Without it a jar embeds the build time, so a rebuild can
|
||||
never match what was published. Bump at each release. -->
|
||||
<project.build.outputTimestamp>2026-10-21T17:23:00Z</project.build.outputTimestamp>
|
||||
<!-- The runway-spi (and runway-spi-testkit) version this plugin compiles and tests against, from ~/.m2. -->
|
||||
<runway.version>1.0.0</runway.version>
|
||||
<!-- The search plugin this engine compiles against, `provided` from ~/.m2 (install it first:
|
||||
`mvn -o -DskipTests install` in ../search — the verify script does). plugin.yml declares
|
||||
`search >= 2.2.0` (3.2.0: the box submits to the results page in its page's language, so a
|
||||
language's index is reached); 2.1.0 was the first whose SearchHit carries the matched words (the
|
||||
constructor this engine calls), and an older search does not compile this plugin. Provided, never bundled: a second copy of the search SPI classes would break by-type lookup. -->
|
||||
<search.version>2.3.0</search.version>
|
||||
<!-- The EXACT Lucene version this plugin is compiled against; lucene-provider must ship the same one
|
||||
(plugin.yml pins `lucene-provider == 10.4.0`). Keep these two in lock-step. -->
|
||||
<lucene.version>10.4.0</lucene.version>
|
||||
</properties>
|
||||
|
||||
<dependencies>
|
||||
<!-- The dependency-free extension API (SPI interfaces, services and immutable model records). -->
|
||||
<dependency>
|
||||
<groupId>mx.quest</groupId>
|
||||
<artifactId>runway-spi</artifactId>
|
||||
<version>${runway.version}</version>
|
||||
</dependency>
|
||||
|
||||
<!-- NO runway-app dependency, in any scope: the plugin links only the SPI, so a host
|
||||
import no longer compiles and the kernel's host-linkage scanner finds nothing to report. -->
|
||||
<dependency>
|
||||
<groupId>mx.quest</groupId>
|
||||
<artifactId>runway-spi-testkit</artifactId>
|
||||
<version>${runway.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<!-- The `search` plugin publishes the SiteSearchEngine SPI this plugin implements and the SearchCorpus it
|
||||
indexes. Compile-only: at runtime the shared plugin classloader supplies search's classes (both
|
||||
plugin jars load into ONE classloader, so the SPI has one Class identity), and `requires: search`
|
||||
in plugin.yml makes it a HARD load gate. `provided` from ~/.m2 (install ../search first), and never
|
||||
bundled: the assembly below copies this plugin's own jar only. -->
|
||||
<dependency>
|
||||
<groupId>mx.quest</groupId>
|
||||
<artifactId>runway-plugin-search</artifactId>
|
||||
<version>${search.version}</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter</artifactId>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
|
||||
<!-- Lucene — supplied at RUNTIME by the lucene-provider plugin on the shared classloader. PROVIDED here:
|
||||
compile-only, never bundled into this plugin's own lib/ (that would be a second copy on the shared
|
||||
classloader). requires: lucene-provider == 10.4.0 in plugin.yml guarantees the exact binaries. -->
|
||||
<dependency>
|
||||
<groupId>org.apache.lucene</groupId>
|
||||
<artifactId>lucene-core</artifactId>
|
||||
<version>${lucene.version}</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.lucene</groupId>
|
||||
<artifactId>lucene-analysis-common</artifactId>
|
||||
<version>${lucene.version}</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.lucene</groupId>
|
||||
<artifactId>lucene-highlighter</artifactId>
|
||||
<version>${lucene.version}</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
|
||||
<!-- Tests DO run the real Lucene: at test time it must be on the classpath, so the same jars come in as
|
||||
`test` scope too (provided is not visible to the test classpath on its own). These are the exact
|
||||
10.4.0 artifacts lucene-provider ships, so the tests exercise the runtime binaries faithfully. -->
|
||||
<dependency>
|
||||
<groupId>org.apache.lucene</groupId>
|
||||
<artifactId>lucene-memory</artifactId>
|
||||
<version>${lucene.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.lucene</groupId>
|
||||
<artifactId>lucene-queries</artifactId>
|
||||
<version>${lucene.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-test</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<finalName>runway-plugin-search-lucene</finalName>
|
||||
<plugins>
|
||||
<!-- Assemble both installable forms: target/search-lucene/ (folder) and the UI zip. NOTE: NO lib/ —
|
||||
Lucene is NOT bundled here; it comes from the lucene-provider plugin at runtime. -->
|
||||
<plugin>
|
||||
<artifactId>maven-antrun-plugin</artifactId>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>assemble-plugin-folder</id>
|
||||
<phase>package</phase>
|
||||
<goals>
|
||||
<goal>run</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<target>
|
||||
<property name="stage" value="${project.build.directory}/search-lucene"/>
|
||||
<delete dir="${stage}"/>
|
||||
<mkdir dir="${stage}"/>
|
||||
<copy file="${project.basedir}/plugin.yml" todir="${stage}"/>
|
||||
<copy file="${project.basedir}/LICENSE" todir="${stage}"/>
|
||||
<copy file="${project.basedir}/LICENSE-EXCEPTION" todir="${stage}"/>
|
||||
<copy file="${project.build.directory}/runway-plugin-search-lucene.jar" todir="${stage}"/>
|
||||
<copy todir="${stage}/templates">
|
||||
<fileset dir="${project.basedir}/templates"/>
|
||||
</copy>
|
||||
<copy todir="${stage}/i18n">
|
||||
<fileset dir="${project.basedir}/i18n"/>
|
||||
</copy>
|
||||
<touch datetime="${project.build.outputTimestamp}"
|
||||
pattern="yyyy-MM-dd'T'HH:mm:ss'Z'">
|
||||
<fileset dir="${stage}"/>
|
||||
<dirset dir="${stage}"/>
|
||||
<dirset dir="${project.build.directory}" includes="search-lucene"/>
|
||||
</touch>
|
||||
<zip destfile="${project.build.directory}/runway-plugin-search-lucene-${project.version}.zip">
|
||||
<zipfileset dir="${project.build.directory}" includes="search-lucene/**"/>
|
||||
</zip>
|
||||
<echo message="Staged install folder (thin jar, NO bundled Lucene — from lucene-provider): ${stage}"/>
|
||||
<echo message="UI-uploadable archive: ${project.build.directory}/runway-plugin-search-lucene-${project.version}.zip"/>
|
||||
</target>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
</project>
|
||||
+316
@@ -0,0 +1,316 @@
|
||||
#!/usr/bin/env bash
|
||||
# Prove this release's contract end to end on the PACKAGED Runway host, together with the two plugins it
|
||||
# requires — the current search (publishes SiteSearchEngine, SearchCorpus and SearchHit.terms) and the code-less
|
||||
# lucene-provider (the Lucene binaries) — and, when BASELINE_REF is set, prove that it ranks exactly as the baseline:
|
||||
#
|
||||
# 1. BASELINE (only when BASELINE_REF is set): search 2.0.0 + search-lucene 3.0.0 (built from git, BASELINE_REF) +
|
||||
# lucene-provider on the same host jar, a fixture site (pages written for the tiers, stemming, fuzzy and the
|
||||
# exclusion list, a stored ranking knob), and a fixed set of queries answered by the JSON API.
|
||||
# 2. CURRENT: the current search + this release + lucene-provider, the same fixture and queries, with the index on
|
||||
# DISK this time (the app-level settings bind). Every answer — order, URLs, titles, snippets, scores — must be
|
||||
# byte-identical to the baseline's (the link and terms fields 3.0.0 never had are set aside for the comparison;
|
||||
# they are checked on their own: each hit carries the words it matched, as the page writes them).
|
||||
# 3. On the current deployment: the three plugins load with ZERO host-linkage and bean-name/surface warnings, the
|
||||
# console card and admin fragment render (bean @searchLuceneAdminModel), a settings save of the search plugin's
|
||||
# exclude list and of this plugin's own knobs reach the next query without a reindex, and the operator's reindex
|
||||
# POST rebuilds this index and reports its size.
|
||||
#
|
||||
# Only the search plugin is installed to ~/.m2 (it is this plugin's compile-time dependency, as in 2.x); everything
|
||||
# else is PACKAGED offline. Formerly: this plugin compiled against the
|
||||
# search jar its sibling folder just built. Verify ONLY against the packaged jar — never spring-boot:run (its restart
|
||||
# classloader loads ZERO plugins).
|
||||
#
|
||||
# Usage: scripts/verify-against-host.sh [--keep] [--port N]
|
||||
# JAVA_HOME=/path/to/jdk-25 required: the JDK that builds the plugin and runs the host
|
||||
# MVN=/path/to/mvn Maven (default: mvn on the PATH)
|
||||
# HOST_TARGET=/path/to/runway/runway-app/target the host build (default: the kernel this plugin sits in, else ../runway)
|
||||
# HOST_JAR=/path/to/runway-app-<ver>-exec.jar the kernel to verify against (default: the host checkout's
|
||||
# runway-app/target jar MATCHING its pom version)
|
||||
# VERIFY_TMPDIR=/dir where the throwaway deployments go (default: this plugin's target/)
|
||||
# VERIFY_LOG_DIR=/dir keep the host logs, the query answers and the diff there (evidence)
|
||||
# BASELINE_REF=<git ref> the commit carrying search 2.0.0 + search-lucene 3.0.0 (default:
|
||||
# empty, which skips the before/after comparison with a note);
|
||||
# SKIP_BASELINE=1 skips it too
|
||||
set -uo pipefail
|
||||
|
||||
HERE="$(cd "$(dirname "$(readlink -f "$0")")/.." && pwd)"
|
||||
VER="$(sed -n 's/^version: *//p' "$HERE/plugin.yml")" # the release under test
|
||||
REPO="$(cd "$HERE/.." && pwd)"
|
||||
SEARCH="$REPO/search"
|
||||
LUCENE_PROVIDER="$REPO/lucene-provider"
|
||||
# JAVA_HOME must name a JDK 25. MVN (default: `mvn` on the PATH) and HOST_TARGET (default: see above) can be set in the environment.
|
||||
if [ -z "${JAVA_HOME:-}" ] || [ ! -x "$JAVA_HOME/bin/java" ]; then echo "set JAVA_HOME to a JDK 25"; exit 2; fi
|
||||
export JAVA_HOME
|
||||
JAVA="$JAVA_HOME/bin/java"
|
||||
MVN="${MVN:-mvn}"
|
||||
# Default host: the kernel at the root of the repository this plugin sits in (plugins/<name>/), else a kernel
|
||||
# checkout named `runway` beside the plugins checkout.
|
||||
if [ -z "${HOST_TARGET:-}" ]; then
|
||||
if [ -f "$HERE/../../../runway-app/pom.xml" ]; then HOST_TARGET="$HERE/../../../runway-app/target"
|
||||
else HOST_TARGET="$HERE/../../runway/runway-app/target"; fi
|
||||
fi
|
||||
BASELINE_REF="${BASELINE_REF:-}"
|
||||
if [ -z "$BASELINE_REF" ] && [ "${SKIP_BASELINE:-0}" != 1 ]; then
|
||||
echo "[verify] BASELINE_REF is not set: skipping the comparison with search 2.0.0 + search-lucene 3.0.0" \
|
||||
"(set BASELINE_REF to a commit carrying those two versions to run it)"
|
||||
SKIP_BASELINE=1
|
||||
fi
|
||||
M2="${HOME}/.m2/repository/mx/quest"
|
||||
|
||||
KEEP="no"; PORT=""
|
||||
while [ $# -gt 0 ]; do case "$1" in
|
||||
--keep) KEEP="yes"; shift ;;
|
||||
--port) PORT="${2:?}"; shift 2 ;;
|
||||
*) echo "unknown arg: $1"; exit 2 ;;
|
||||
esac; done
|
||||
|
||||
APP_USER=root; APP_PW=Lucene-Admin-2026; SITE_USER=owner; SITE_PW=Lucene-Site-2026
|
||||
free_port() { python3 -I -c 'import socket;s=socket.socket();s.bind(("127.0.0.1",0));print(s.getsockname()[1]);s.close()'; }
|
||||
[ -n "$PORT" ] || PORT="$(free_port)"
|
||||
BASE="http://localhost:$PORT"
|
||||
|
||||
m2_before="$(ls -d "$M2"/runway-plugin-search-lucene/"$VER" 2>/dev/null)"
|
||||
|
||||
echo "[verify] packaging search (the plugin this one requires and compiles against) ..."
|
||||
( cd "$SEARCH" && "$MVN" -o -q -DskipTests install ) || { echo "search build/install failed"; exit 1; }
|
||||
echo "[verify] packaging lucene-provider ..."
|
||||
( cd "$LUCENE_PROVIDER" && "$MVN" -o -q -DskipTests package ) || { echo "lucene-provider build failed"; exit 1; }
|
||||
echo "[verify] packaging this plugin ..."
|
||||
( cd "$HERE" && "$MVN" -o -q -DskipTests package ) || { echo "search-lucene build failed"; exit 1; }
|
||||
|
||||
# The host jar MATCHING the host pom's version — never "the newest file": every reproducible jar carries the same
|
||||
# fixed timestamp, so `ls -t` cannot tell a leftover release jar from the SNAPSHOT under test.
|
||||
if [ -n "${HOST_JAR:-}" ]; then
|
||||
JAR="$HOST_JAR"
|
||||
else
|
||||
HOST_VERSION="$(sed -n 's:.*<version>\(.*\)</version>.*:\1:p' "$HOST_TARGET/../pom.xml" | head -1)"
|
||||
JAR="$HOST_TARGET/runway-app-$HOST_VERSION-exec.jar"
|
||||
fi
|
||||
[ -f "$JAR" ] || { echo "no host exec jar $JAR — build the host (mvn -pl runway-app package) or set HOST_JAR"; exit 1; }
|
||||
echo "[verify] host jar: $JAR"
|
||||
|
||||
mkdir -p "${VERIFY_TMPDIR:-$HERE/target}"
|
||||
SCRATCH="$(mktemp -d "${VERIFY_TMPDIR:-$HERE/target}/lucene-verify.XXXXXX")"
|
||||
PID=""
|
||||
stop_host() { [ -z "$PID" ] || { kill "$PID" 2>/dev/null; wait "$PID" 2>/dev/null; PID=""; }; }
|
||||
cleanup() {
|
||||
if [ -n "${VERIFY_LOG_DIR:-}" ]; then
|
||||
mkdir -p "$VERIFY_LOG_DIR"
|
||||
for run in before after; do
|
||||
[ -d "$SCRATCH/$run" ] || continue
|
||||
mkdir -p "$VERIFY_LOG_DIR/$run"
|
||||
cp "$SCRATCH/$run"/*.log "$VERIFY_LOG_DIR/$run/" 2>/dev/null
|
||||
[ -d "$SCRATCH/$run/answers" ] && cp -r "$SCRATCH/$run/answers" "$VERIFY_LOG_DIR/$run/"
|
||||
done
|
||||
cp "$SCRATCH"/*.txt "$VERIFY_LOG_DIR/" 2>/dev/null
|
||||
fi
|
||||
# Wait for the host to exit before deleting: a JVM still shutting down rewrites files under external/.
|
||||
[ "$KEEP" = "yes" ] || { stop_host; rm -rf "$SCRATCH"; }
|
||||
}
|
||||
trap cleanup EXIT
|
||||
|
||||
wait_for() { for _ in $(seq 1 "$3"); do grep -q "$2" "$1" 2>/dev/null && return 0; sleep 1; done; return 1; }
|
||||
PASS=0; FAIL=0
|
||||
ck() { if eval "$2" >/dev/null 2>&1; then echo " PASS $1"; PASS=$((PASS+1)); else echo " FAIL $1"; FAIL=$((FAIL+1)); fi; }
|
||||
code() { curl -s -o /dev/null -w '%{http_code}' "$@"; }
|
||||
|
||||
# --- The fixture: pages written for the tiers, stemming, fuzzy, highlighting and the exclusion list ------------------
|
||||
page() { # sites-dir slug title description body-html
|
||||
local t="$1/default/templates"
|
||||
printf 'path: /%s\ntemplate: _master\ntitle:\n en: "%s"\ndescription:\n en: "%s"\n' "$2" "$3" "$4" > "$t/$2.meta.yml"
|
||||
printf '<!DOCTYPE html>\n<html lang="en">\n<head><title>%s</title></head>\n<body>\n<header id="site-header"></header>\n<main id="content">\n%s\n</main>\n<footer id="site-footer"></footer>\n</body>\n</html>\n' \
|
||||
"$3" "$5" > "$t/$2.html"
|
||||
cp "$t/about.th.xml" "$t/$2.th.xml"
|
||||
}
|
||||
fixture() { # sites-dir
|
||||
page "$1" guide "Runway Deployment Guide" "How to deploy Runway in production." \
|
||||
"<p>This guide covers the deployment of runway on a single server. Read the runway deployment guide first.</p>"
|
||||
page "$1" manual "Manual" "" "<p>The cloud deployment guide explains everything about the cloud.</p>"
|
||||
page "$1" notes "Notes" "Miscellaneous" \
|
||||
"<p>cloud infrastructure. a long unrelated paragraph about many topics. deployment pipelines. yet another sentence entirely. a helpful guide to nothing.</p>"
|
||||
page "$1" athletics "Athletics" "Sports club" "<p>They run every morning and they ran yesterday.</p>"
|
||||
page "$1" handbook "Lucene Handbook" "Search internals" "<p>All about lucene, analyzers and <mark> tags.</p>"
|
||||
page "$1" pricing "Pricing" "Plans for runway hosting" "<p>Runway hosting plans start small. Deployment support included.</p>"
|
||||
page "$1" privacy "Privacy" "Runway privacy policy" "<p>runway runway privacy deployment guide</p>"
|
||||
# A bilingual page whose copy comes ONLY from the site's bundles (decoupled th:text; the template's element is
|
||||
# empty) -- the kernel indexes it as rendered per language, and this plugin keeps one index per
|
||||
# language. Its words appear in none of QUERIES, so the 3.0.0 comparison is unaffected.
|
||||
sed -i '/^locales:/a - "es"' "$1/default/site.yml"
|
||||
local t="$1/default/templates"
|
||||
printf 'path: /faculty\nlocalizedPaths:\n es: /facultad\nlocales: [en, es]\ntemplate: _master\ntitle:\n en: Faculty\n es: Profesores\n' > "$t/faculty.meta.yml"
|
||||
printf '<!DOCTYPE html>\n<html lang="en">\n<head><title>Faculty</title></head>\n<body>\n<header id="site-header"></header>\n<main id="content"><p id="faculty-copy"></p></main>\n<footer id="site-footer"></footer>\n</body>\n</html>\n' > "$t/faculty.html"
|
||||
sed 's#</thlogic># <attr sel="\#faculty-copy" th:text="\#{verify.faculty}"/>\n</thlogic>#' "$t/about.th.xml" > "$t/faculty.th.xml"
|
||||
mkdir -p "$1/default/i18n"
|
||||
printf '\nverify.faculty=Our students learn from researchers.\n' >> "$1/default/i18n/messages.properties"
|
||||
printf '\nverify.faculty=Nuestros alumnos aprenden con una facultad de excelencia.\n' >> "$1/default/i18n/messages_es.properties"
|
||||
mkdir -p "$1/default/plugins"
|
||||
printf 'exclude:\n - privacy\n' > "$1/default/plugins/search.yml"
|
||||
printf 'titleBoost: 9.5\n' > "$1/default/plugins/search-lucene.yml"
|
||||
}
|
||||
QUERIES=("runway" "deployment" "cloud%20deployment%20guide" "runway%20deployment%20guide" "running" "lucane"
|
||||
"privacy" "hosting%20plans" "mark" "about" "home" "xyzzy%20nothing")
|
||||
ask_all() { # out-dir
|
||||
mkdir -p "$1"
|
||||
local i=0
|
||||
for q in "${QUERIES[@]}"; do
|
||||
curl -s "$BASE/search/api?q=$q" > "$1/$(printf '%02d' "$i")-${q//%20/_}.json"
|
||||
i=$((i + 1))
|
||||
done
|
||||
}
|
||||
|
||||
# --- One throwaway deployment: wizard, fixture, ACTIVE boot ----------------------------------------------------------
|
||||
boot() { # log-file (uses DEPLOY_DIR and EXT)
|
||||
( cd "$DEPLOY_DIR" && exec "$JAVA" -jar "$JAR" --server.port="$PORT" --runway.storage.external="$EXT" ) >"$1" 2>&1 &
|
||||
PID=$!
|
||||
}
|
||||
deploy() { # run-name search-folder lucene-folder [app-level search-lucene.yml]
|
||||
DEPLOY_DIR="$SCRATCH/$1"; EXT="$DEPLOY_DIR/external"; SITES="$EXT/sites"; LOG="$DEPLOY_DIR/active.log"
|
||||
mkdir -p "$EXT/plugins" "$EXT/plugin-settings"
|
||||
cp -r "$2" "$EXT/plugins/search"
|
||||
cp -r "$LUCENE_PROVIDER/target/lucene-provider" "$EXT/plugins/lucene-provider"
|
||||
cp -r "$3" "$EXT/plugins/search-lucene"
|
||||
echo "[verify] $1: booting host (wizard) on :$PORT ..."
|
||||
boot "$DEPLOY_DIR/wizard.log"
|
||||
wait_for "$DEPLOY_DIR/wizard.log" "Started RunwayApplication" 90 \
|
||||
|| { echo "wizard did not start"; tail -20 "$DEPLOY_DIR/wizard.log"; exit 1; }
|
||||
curl -s -o /dev/null -X POST "$BASE/setup" --data-urlencode "username=$APP_USER" --data-urlencode "password=$APP_PW" \
|
||||
--data-urlencode "displayName=Root" --data-urlencode "siteAdminUsername=$SITE_USER" \
|
||||
--data-urlencode "siteAdminPassword=$SITE_PW"
|
||||
for _ in $(seq 1 30); do kill -0 "$PID" 2>/dev/null || break; sleep 1; done
|
||||
stop_host
|
||||
[ -f "$SITES/default/templates/about.th.xml" ] || { echo "the wizard did not seed $SITES/default"; exit 1; }
|
||||
fixture "$SITES"
|
||||
# A generous query ceiling: the comparison asks the same questions on both deployments.
|
||||
printf 'runway:\n plugin:\n search:\n "rate-limit.per-ip-per-minute": 100000\n "rate-limit.per-ip-per-hour": 100000\n' \
|
||||
> "$EXT/plugin-settings/search.yml"
|
||||
[ -z "${4:-}" ] || printf '%s\n' "$4" > "$EXT/plugin-settings/search-lucene.yml"
|
||||
echo "[verify] $1: booting host (ACTIVE) ..."
|
||||
boot "$LOG"
|
||||
wait_for "$LOG" "Started RunwayApplication" 90 || { echo "ACTIVE did not start"; tail -20 "$LOG"; exit 1; }
|
||||
}
|
||||
|
||||
# --- 1. The baseline: search 2.0.0 + search-lucene 3.0.0 -------------------------------------------------------------
|
||||
if [ "${SKIP_BASELINE:-0}" != 1 ]; then
|
||||
echo "[verify] building the baseline (search + search-lucene at $BASELINE_REF) offline ..."
|
||||
SRC="$SCRATCH/baseline-src"
|
||||
mkdir -p "$SRC"
|
||||
git -C "$REPO" archive "$BASELINE_REF" search search-lucene | tar -x -C "$SRC" \
|
||||
|| { echo "cannot read $BASELINE_REF from git"; exit 1; }
|
||||
grep -q '^version: 3.0.0' "$SRC/search-lucene/plugin.yml" && grep -q '^version: 2.0.0' "$SRC/search/plugin.yml" \
|
||||
|| { echo "$BASELINE_REF does not carry search 2.0.0 + search-lucene 3.0.0"; exit 1; }
|
||||
( cd "$SRC/search" && "$MVN" -o -q -DskipTests package ) >"$SCRATCH/baseline-build.txt" 2>&1 \
|
||||
&& ( cd "$SRC/search-lucene" && "$MVN" -o -q -DskipTests package ) >>"$SCRATCH/baseline-build.txt" 2>&1 \
|
||||
|| { echo "baseline build failed (see baseline-build.txt)"; tail -20 "$SCRATCH/baseline-build.txt"; exit 1; }
|
||||
deploy before "$SRC/search/target/search" "$SRC/search-lucene/target/search-lucene"
|
||||
ck "baseline: 3 plugins registered, 0 blocked" "grep -qE 'plugins: 3 registered, 0 blocked' '$LOG'"
|
||||
ck "baseline: the fixture pages serve" "[ \"\$(code '$BASE/guide')\" = 200 ] && [ \"\$(code '$BASE/handbook')\" = 200 ]"
|
||||
ask_all "$SCRATCH/before/answers"
|
||||
grep -E ' WARN ' "$LOG" | grep -E "plugin 'search-lucene'|uses host internals" > "$SCRATCH/baseline-warnings.txt"
|
||||
echo " (search-lucene 3.0.0 drew $(grep -c "search-lucene" "$SCRATCH/baseline-warnings.txt") warning line(s) naming it)"
|
||||
stop_host
|
||||
fi
|
||||
|
||||
# --- 2. The release under test: the current search + this release, index on disk -----------------------------------
|
||||
INDEX_ROOT="$SCRATCH/after/lucene-index"
|
||||
deploy after "$SEARCH/target/search" "$HERE/target/search-lucene" \
|
||||
"$(printf 'runway:\n plugin:\n search-lucene:\n storage: disk\n indexRoot: "%s"' "$INDEX_ROOT")"
|
||||
|
||||
echo "== plugin load (this release's contract) =="
|
||||
ck "3 plugins registered, 0 blocked" "grep -qE 'plugins: 3 registered, 0 blocked' '$LOG'"
|
||||
ck "search-lucene not blocked / quarantined" "! grep -qE \"plugin 'search-lucene' is blocked|plugin-quarantine\" '$LOG'"
|
||||
# Host linkage and the surface rules, in both kernels' words: SPI 0.6.0 WARNed ("uses host internals", "… allowed until
|
||||
# Runway 1.0"); from SPI 1.0.0 the kernel BLOCKS and logs "linkage scan: <reason>" / the surface reason — a grep for the
|
||||
# 0.6.0 wording alone can never fail on a 1.0 kernel.
|
||||
ck "ZERO host-linkage findings" "! grep -qE \"uses host internals|plugin '(search-lucene|search)' linkage scan\" '$LOG'"
|
||||
ck "ZERO bean-name/surface findings" "! grep -qE \"plugin '(search-lucene|search)'.*(allowed until Runway 1.0|bean name|may not contribute)\" '$LOG'"
|
||||
ck "no WARN/ERROR names the plugin" "! grep -E ' (WARN|ERROR) ' '$LOG' | grep -qiE \"search-lucene|mx\\.quest\\.searchlucene\""
|
||||
ck "no collision / degraded / missing class" "! grep -qiE 'collision|duplicate key|degraded|NoClassDefFound|ClassNotFound' '$LOG'"
|
||||
ck "Lucene is NOT bundled in search-lucene" "[ ! -d '$EXT/plugins/search-lucene/lib' ]"
|
||||
ck "the fixture pages serve" "[ \"\$(code '$BASE/guide')\" = 200 ] && [ \"\$(code '$BASE/handbook')\" = 200 ]"
|
||||
ck "no plugin-owned /search page (404)" "[ \"\$(code '$BASE/search?q=runway')\" = 404 ]"
|
||||
|
||||
echo "== ranking: the same answers as 3.0.0 =="
|
||||
ask_all "$SCRATCH/after/answers"
|
||||
ck "the Lucene engine serves (a 1-edit typo finds the handbook)" "grep -q '\"url\":\"/handbook\"' '$SCRATCH/after/answers/05-lucane.json'"
|
||||
ck "the search plugin's exclusion applies through SearchCorpus (no /privacy for 'runway')" \
|
||||
"grep -q '\"url\":\"/guide\"' '$SCRATCH/after/answers/00-runway.json' && ! grep -q '/privacy' '$SCRATCH/after/answers/00-runway.json'"
|
||||
ck "each hit carries the words it matched and a link marked with them" \
|
||||
"grep -qE '\"link\":\"/[^\"]*#rw-hl=[^\"]+\",\"terms\":\\[\"[^\"]+' '$SCRATCH/after/answers/04-running.json'"
|
||||
ck "…as the page writes them, at least every word its snippet marks (running: run, and ran within one edit)" \
|
||||
"python3 -I -c 'import json,re,sys; r=json.load(open(sys.argv[1]))[\"results\"]; ok=all(h[\"terms\"] and set(m.lower() for m in re.findall(\"<mark>(.*?)</mark>\", h[\"snippet\"])) <= set(h[\"terms\"]) for h in r); sys.exit(0 if r and ok else 1)' '$SCRATCH/after/answers/04-running.json'"
|
||||
if [ "${SKIP_BASELINE:-0}" != 1 ]; then
|
||||
# 3.0.0 predates link/terms (search 2.1.0): compare everything else, byte for byte.
|
||||
mkdir -p "$SCRATCH/after/compared"
|
||||
for f in "$SCRATCH"/after/answers/*.json; do
|
||||
python3 -I -c 'import re,sys; s=open(sys.argv[1],encoding="utf-8").read(); sys.stdout.write(re.sub(r",\"link\":\"(?:[^\"\\\\]|\\\\.)*\",\"terms\":\[(?:\"(?:[^\"\\\\]|\\\\.)*\",?)*\]", "", s))' \
|
||||
"$f" > "$SCRATCH/after/compared/$(basename "$f")"
|
||||
done
|
||||
diff -r "$SCRATCH/before/answers" "$SCRATCH/after/compared" > "$SCRATCH/ranking-diff.txt"
|
||||
ck "every answer (order, URLs, titles, snippets, scores) is byte-identical to 3.0.0's (${#QUERIES[@]} queries)" \
|
||||
"[ ! -s '$SCRATCH/ranking-diff.txt' ] && [ \$(ls '$SCRATCH/after/answers' | wc -l) = ${#QUERIES[@]} ]"
|
||||
ck "…and the answers are not trivially empty" "[ \$(cat '$SCRATCH'/after/answers/*.json | grep -o '\"url\"' | wc -l) -ge 15 ]"
|
||||
fi
|
||||
|
||||
echo "== one index per language, bundle strings included =="
|
||||
ck "the page's Spanish copy is rendered from the bundle (fixture)" "curl -s '$BASE/es/facultad' | grep -q 'facultad de excelencia'"
|
||||
curl -s "$BASE/search/api?q=excelencia&lang=es" > "$SCRATCH/after/es.json"
|
||||
ck "a Spanish bundle string is found in Spanish, at the Spanish address, with the Spanish title" \
|
||||
"grep -q '\"url\":\"/es/facultad\"' '$SCRATCH/after/es.json' && grep -q '\"title\":\"Profesores\"' '$SCRATCH/after/es.json'"
|
||||
ck "the Spanish analyzer stems ('facultades' finds 'facultad')" \
|
||||
"curl -s '$BASE/search/api?q=facultades&lang=es' | grep -q '\"url\":\"/es/facultad\"'"
|
||||
ck "the English analyzer stems ('researcher' finds 'researchers')" \
|
||||
"curl -s '$BASE/search/api?q=researcher&lang=en' | grep -q '\"url\":\"/faculty\"'"
|
||||
ck "English does not search the Spanish text" "! curl -s '$BASE/search/api?q=excelencia&lang=en' | grep -q '/faculty'"
|
||||
ck "a page in English only is still found from Spanish" \
|
||||
"curl -s '$BASE/search/api?q=lucene&lang=es' | grep -q '\"url\":\"/handbook\"'"
|
||||
|
||||
echo "== storage: the app-level settings bind (disk) =="
|
||||
ck "the site's index lives on disk under indexRoot/default, one folder per language" \
|
||||
"[ -d '$INDEX_ROOT/default/en' ] && [ -d '$INDEX_ROOT/default/es' ] && ls '$INDEX_ROOT/default/es' | grep -q ."
|
||||
|
||||
echo "== the console (signed in as the site owner) =="
|
||||
token() { grep -o 'name="_csrf" value="[^"]*"' | head -1 | sed 's/.*value="//; s/"$//'; }
|
||||
sc() { curl -s -H 'Accept-Language: en' -c "$SCRATCH/cookies.jar" -b "$SCRATCH/cookies.jar" "$@"; }
|
||||
sc -o /dev/null -X POST "$BASE/login" --data-urlencode "username=$SITE_USER" --data-urlencode "password=$SITE_PW" \
|
||||
--data-urlencode "_csrf=$(sc "$BASE/login" | token)"
|
||||
LS="$BASE/__admin/plugins/search-lucene/settings"
|
||||
sc "$LS" > "$SCRATCH/lucene-settings-0.html"
|
||||
DOCS="$(sed -n 's:.*id="la-pages"[^>]*>\([0-9]*\)<.*:\1:p' "$SCRATCH/lucene-settings-0.html" | head -1)"
|
||||
ck "the admin fragment renders (bean @searchLuceneAdminModel): engine search/lucene" \
|
||||
"grep -q 'id=\"la-engine\"[^>]*>search/lucene<' '$SCRATCH/lucene-settings-0.html'"
|
||||
ck "…the indexed-item count (${DOCS:-none})" "[ -n '$DOCS' ] && [ '$DOCS' -ge 8 ]"
|
||||
ck "…the storage mode (disk)" "grep -q 'id=\"la-storage\"[^>]*>disk<' '$SCRATCH/lucene-settings-0.html'"
|
||||
ck "…and the stored title boost (9.5)" "grep -q 'id=\"la-boost\"[^>]*>9.5<' '$SCRATCH/lucene-settings-0.html'"
|
||||
sc -L "$BASE/__admin" > "$SCRATCH/dashboard.html"
|
||||
ck "the dashboard card renders the count" "grep -q 'id=\"lc-pages\"[^>]*>$DOCS<' '$SCRATCH/dashboard.html'"
|
||||
|
||||
echo "== settings saves reach the next query, without a reindex =="
|
||||
SS="$BASE/__admin/plugins/search/settings"
|
||||
sc -o /dev/null -X POST "$SS" --data-urlencode "enabled=true" --data-urlencode "exclude=guide" \
|
||||
--data-urlencode "_csrf=$(sc "$SS" | token)"
|
||||
curl -s "$BASE/search/api?q=runway%20deployment%20guide" > "$SCRATCH/after-exclude.json"
|
||||
ck "search's exclude list saved (guide in, privacy out of the list)" \
|
||||
"grep -q 'guide' '$SITES/default/plugins/search.yml' && ! grep -q 'privacy' '$SITES/default/plugins/search.yml'"
|
||||
ck "…the newly excluded page leaves this index at once" "! grep -q '\"url\":\"/guide\"' '$SCRATCH/after-exclude.json'"
|
||||
ck "…and the no-longer-excluded page joins it" "grep -q '\"url\":\"/privacy\"' '$SCRATCH/after-exclude.json'"
|
||||
sc -o /dev/null -X POST "$LS" --data-urlencode "fuzzy=false" --data-urlencode "titleBoost=9.5" \
|
||||
--data-urlencode "_csrf=$(token < "$SCRATCH/lucene-settings-0.html")"
|
||||
ck "this plugin's knobs saved (fuzzy off)" "grep -q 'fuzzy: false' '$SITES/default/plugins/search-lucene.yml'"
|
||||
ck "…the typo no longer matches on the next query" "curl -s '$BASE/search/api?q=lucane' | grep -q '\"count\":0'"
|
||||
ck "…while the exact term still does" "curl -s '$BASE/search/api?q=lucene' | grep -q '\"url\":\"/handbook\"'"
|
||||
|
||||
echo "== the operator's reindex rebuilds this index =="
|
||||
sc "$SS" > "$SCRATCH/search-settings.html"
|
||||
sc -X POST "$BASE/search/reindex" --data-urlencode "_csrf=$(token < "$SCRATCH/search-settings.html")" > "$SCRATCH/reindex.txt"
|
||||
ck "POST /search/reindex reports this engine's fresh count (${DOCS:-none})" "grep -qx 'Search index rebuilt\\. ($DOCS)' '$SCRATCH/reindex.txt'"
|
||||
ck "a GET does not reindex (404)" "[ \"\$(sc -o /dev/null -w '%{http_code}' '$BASE/search/reindex')\" = 404 ]"
|
||||
|
||||
echo "== the build wrote nothing to the local Maven repository =="
|
||||
m2_after="$(ls -d "$M2"/runway-plugin-search-lucene/"$VER" 2>/dev/null)"
|
||||
ck "search-lucene itself is never installed to ~/.m2 (only its compile dependency, search, is)" "[ -z '$m2_after' ] || [ '$m2_after' = '$m2_before' ]"
|
||||
|
||||
ck "still no WARN/ERROR names the plugin after the run" "! grep -E ' (WARN|ERROR) ' '$LOG' | grep -qiE \"search-lucene|mx\\.quest\\.searchlucene\""
|
||||
|
||||
echo; echo "RESULT: $PASS passed, $FAIL failed"
|
||||
if [ "$KEEP" = "yes" ]; then echo "[verify] kept at $BASE (scratch $SCRATCH; kill $PID to stop)"; wait "$PID"; fi
|
||||
exit "$FAIL"
|
||||
@@ -0,0 +1,33 @@
|
||||
package mx.quest.searchlucene;
|
||||
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
* Reduces a page's raw HTML source to indexable plain text: drops {@code <script>}/{@code <style>} blocks and
|
||||
* comments, strips the remaining tags, decodes a handful of common entities, and collapses whitespace. This is
|
||||
* a best-effort text extraction for full-text indexing — not a strict HTML parser — so a malformed page still
|
||||
* yields reasonable searchable text.
|
||||
*/
|
||||
final class HtmlText {
|
||||
|
||||
private static final Pattern SCRIPT_STYLE =
|
||||
Pattern.compile("(?is)<(script|style)\\b[^>]*>.*?</\\1>");
|
||||
private static final Pattern COMMENT = Pattern.compile("(?s)<!--.*?-->");
|
||||
private static final Pattern TAG = Pattern.compile("<[^>]+>");
|
||||
private static final Pattern WS = Pattern.compile("\\s+");
|
||||
|
||||
private HtmlText() {
|
||||
}
|
||||
|
||||
static String toText(String html) {
|
||||
if (html == null || html.isBlank()) {
|
||||
return "";
|
||||
}
|
||||
String s = SCRIPT_STYLE.matcher(html).replaceAll(" ");
|
||||
s = COMMENT.matcher(s).replaceAll(" ");
|
||||
s = TAG.matcher(s).replaceAll(" ");
|
||||
s = s.replace(" ", " ").replace("&", "&").replace("<", "<").replace(">", ">")
|
||||
.replace(""", "\"").replace("'", "'").replace("'", "'");
|
||||
return WS.matcher(s).replaceAll(" ").strip();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
package mx.quest.searchlucene;
|
||||
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.ConcurrentMap;
|
||||
import java.util.function.Supplier;
|
||||
import org.apache.lucene.analysis.Analyzer;
|
||||
import org.apache.lucene.analysis.ar.ArabicAnalyzer;
|
||||
import org.apache.lucene.analysis.bg.BulgarianAnalyzer;
|
||||
import org.apache.lucene.analysis.ca.CatalanAnalyzer;
|
||||
import org.apache.lucene.analysis.cz.CzechAnalyzer;
|
||||
import org.apache.lucene.analysis.da.DanishAnalyzer;
|
||||
import org.apache.lucene.analysis.de.GermanAnalyzer;
|
||||
import org.apache.lucene.analysis.el.GreekAnalyzer;
|
||||
import org.apache.lucene.analysis.en.EnglishAnalyzer;
|
||||
import org.apache.lucene.analysis.es.SpanishAnalyzer;
|
||||
import org.apache.lucene.analysis.eu.BasqueAnalyzer;
|
||||
import org.apache.lucene.analysis.fi.FinnishAnalyzer;
|
||||
import org.apache.lucene.analysis.fr.FrenchAnalyzer;
|
||||
import org.apache.lucene.analysis.gl.GalicianAnalyzer;
|
||||
import org.apache.lucene.analysis.hi.HindiAnalyzer;
|
||||
import org.apache.lucene.analysis.hu.HungarianAnalyzer;
|
||||
import org.apache.lucene.analysis.hy.ArmenianAnalyzer;
|
||||
import org.apache.lucene.analysis.id.IndonesianAnalyzer;
|
||||
import org.apache.lucene.analysis.it.ItalianAnalyzer;
|
||||
import org.apache.lucene.analysis.lt.LithuanianAnalyzer;
|
||||
import org.apache.lucene.analysis.lv.LatvianAnalyzer;
|
||||
import org.apache.lucene.analysis.nl.DutchAnalyzer;
|
||||
import org.apache.lucene.analysis.no.NorwegianAnalyzer;
|
||||
import org.apache.lucene.analysis.pt.PortugueseAnalyzer;
|
||||
import org.apache.lucene.analysis.ro.RomanianAnalyzer;
|
||||
import org.apache.lucene.analysis.ru.RussianAnalyzer;
|
||||
import org.apache.lucene.analysis.standard.StandardAnalyzer;
|
||||
import org.apache.lucene.analysis.sv.SwedishAnalyzer;
|
||||
import org.apache.lucene.analysis.th.ThaiAnalyzer;
|
||||
import org.apache.lucene.analysis.tr.TurkishAnalyzer;
|
||||
|
||||
/**
|
||||
* Chooses a Lucene {@link Analyzer} per content/query language, so a site's pages are tokenized <b>and
|
||||
* stemmed</b> for the language they are written in — a query for {@code "running"} matches a page that says
|
||||
* {@code "run"}, a Spanish query for {@code "corriendo"} matches {@code "correr"}, and so on. Where Lucene ships
|
||||
* a language-specific analyzer (which bundles that language's stopword list and stemmer), that analyzer is used;
|
||||
* for any language Lucene has no analyzer for — or an unknown/blank language — it falls back to
|
||||
* {@link StandardAnalyzer} (tokenize + lowercase, no stemming), which is always correct, just less clever.
|
||||
*
|
||||
* <p><b>Why the same analyzer must be used at index and query time:</b> stemming is an analysis-time transform.
|
||||
* If the index stemmed {@code "running" → "run"} but the query analyzer did not, the query term {@code "running"}
|
||||
* would never match the indexed term {@code "run"}. This class is the single source of truth for "the analyzer
|
||||
* for language X", called from both the indexer and the searcher, so the two can never drift.
|
||||
*
|
||||
* <p>Analyzers are <b>immutable and thread-safe</b> once built, and building one is not free (it reads a
|
||||
* stopword resource), so instances are cached per language key. The lookup key is the lowercased ISO language
|
||||
* code (e.g. {@code "en"}, {@code "es"}); a full {@link Locale} is reduced to its language.
|
||||
*/
|
||||
final class LocaleAnalyzers {
|
||||
|
||||
/** Language code → a factory for that language's analyzer. Absent code ⇒ StandardAnalyzer fallback. */
|
||||
private static final Map<String, Supplier<Analyzer>> BY_LANGUAGE = Map.ofEntries(
|
||||
Map.entry("ar", ArabicAnalyzer::new),
|
||||
Map.entry("bg", BulgarianAnalyzer::new),
|
||||
Map.entry("ca", CatalanAnalyzer::new),
|
||||
Map.entry("cs", CzechAnalyzer::new),
|
||||
Map.entry("da", DanishAnalyzer::new),
|
||||
Map.entry("de", GermanAnalyzer::new),
|
||||
Map.entry("el", GreekAnalyzer::new),
|
||||
Map.entry("en", EnglishAnalyzer::new),
|
||||
Map.entry("es", SpanishAnalyzer::new),
|
||||
Map.entry("eu", BasqueAnalyzer::new),
|
||||
Map.entry("fi", FinnishAnalyzer::new),
|
||||
Map.entry("fr", FrenchAnalyzer::new),
|
||||
Map.entry("gl", GalicianAnalyzer::new),
|
||||
Map.entry("hi", HindiAnalyzer::new),
|
||||
Map.entry("hu", HungarianAnalyzer::new),
|
||||
Map.entry("hy", ArmenianAnalyzer::new),
|
||||
Map.entry("id", IndonesianAnalyzer::new),
|
||||
Map.entry("it", ItalianAnalyzer::new),
|
||||
Map.entry("lt", LithuanianAnalyzer::new),
|
||||
Map.entry("lv", LatvianAnalyzer::new),
|
||||
Map.entry("nl", DutchAnalyzer::new),
|
||||
Map.entry("no", NorwegianAnalyzer::new),
|
||||
Map.entry("pt", PortugueseAnalyzer::new),
|
||||
Map.entry("ro", RomanianAnalyzer::new),
|
||||
Map.entry("ru", RussianAnalyzer::new),
|
||||
Map.entry("sv", SwedishAnalyzer::new),
|
||||
Map.entry("th", ThaiAnalyzer::new),
|
||||
Map.entry("tr", TurkishAnalyzer::new));
|
||||
|
||||
/** Built analyzers, cached by language key. Analyzers are thread-safe, so caching is a pure win. */
|
||||
private final ConcurrentMap<String, Analyzer> cache = new ConcurrentHashMap<>();
|
||||
|
||||
/**
|
||||
* The analyzer for {@code locale}'s language — a stemming language analyzer where Lucene ships one, else
|
||||
* {@link StandardAnalyzer}. Never {@code null}. The returned analyzer is shared and must not be closed by the
|
||||
* caller (the engine owns lifecycle via {@link #close()}).
|
||||
*
|
||||
* @param locale the content/query locale; a {@code null} locale is treated as the standard fallback
|
||||
*/
|
||||
Analyzer forLocale(Locale locale) {
|
||||
String lang = (locale == null) ? "" : locale.getLanguage().toLowerCase(Locale.ROOT);
|
||||
return forLanguage(lang);
|
||||
}
|
||||
|
||||
/** As {@link #forLocale(Locale)} but keyed directly by an ISO language code (blank/unknown ⇒ standard). */
|
||||
Analyzer forLanguage(String language) {
|
||||
String lang = (language == null) ? "" : language.toLowerCase(Locale.ROOT);
|
||||
return cache.computeIfAbsent(lang, k -> {
|
||||
Supplier<Analyzer> factory = BY_LANGUAGE.get(k);
|
||||
return (factory != null) ? factory.get() : new StandardAnalyzer();
|
||||
});
|
||||
}
|
||||
|
||||
/** Whether a genuine language analyzer (with stemming) exists for {@code language} — for the console/tests. */
|
||||
static boolean hasLanguageAnalyzer(String language) {
|
||||
return language != null && BY_LANGUAGE.containsKey(language.toLowerCase(Locale.ROOT));
|
||||
}
|
||||
|
||||
/** Release every cached analyzer (called when the engine is disposed). Idempotent. */
|
||||
void close() {
|
||||
cache.values().forEach(Analyzer::close);
|
||||
cache.clear();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
package mx.quest.searchlucene;
|
||||
|
||||
/**
|
||||
* Read-only status model for the plugin's console surfaces (dashboard card + admin fragment), read by template
|
||||
* bean name, e.g. {@code ${@searchLuceneAdminModel.indexedPages(tenantSiteId)}}. It delegates to the live
|
||||
* {@link LuceneSearchEngine} so the numbers reflect the actual per-site index and effective ranking config.
|
||||
*/
|
||||
public class LuceneAdminModel {
|
||||
|
||||
private final LuceneSearchEngine engine;
|
||||
|
||||
public LuceneAdminModel(LuceneSearchEngine engine) {
|
||||
this.engine = engine;
|
||||
}
|
||||
|
||||
/** How many pages are in this site's Lucene index right now. */
|
||||
public int indexedPages(String siteId) {
|
||||
return engine.indexedDocuments(siteId);
|
||||
}
|
||||
|
||||
/** The engine key (constant) — shown so an operator can confirm which engine is active. */
|
||||
public String engineKey() {
|
||||
return LuceneSearchEngine.KEY;
|
||||
}
|
||||
|
||||
/** The effective title boost applied to this site's queries. */
|
||||
public String titleBoost(String siteId) {
|
||||
return String.valueOf(engine.effectiveTitleBoost(siteId));
|
||||
}
|
||||
|
||||
/** The active index storage mode ({@code heap} or {@code disk}) — an app-level (platform) setting. */
|
||||
public String storageMode() {
|
||||
return engine.storageMode();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,690 @@
|
||||
package mx.quest.searchlucene;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.UncheckedIOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.atomic.AtomicLong;
|
||||
import java.util.regex.Pattern;
|
||||
import mx.quest.runway.spi.model.CatalogEntry;
|
||||
import mx.quest.runway.spi.model.SiteView;
|
||||
import mx.quest.runway.spi.service.PluginSettings;
|
||||
import mx.quest.runway.spi.service.Sites;
|
||||
import mx.quest.search.spi.SearchCorpus;
|
||||
import mx.quest.search.spi.SearchHit;
|
||||
import mx.quest.search.spi.SearchQuery;
|
||||
import mx.quest.search.spi.SiteSearchEngine;
|
||||
import org.apache.lucene.analysis.Analyzer;
|
||||
import org.apache.lucene.analysis.TokenStream;
|
||||
import org.apache.lucene.analysis.tokenattributes.CharTermAttribute;
|
||||
import org.apache.lucene.document.Document;
|
||||
import org.apache.lucene.document.Field;
|
||||
import org.apache.lucene.document.StoredField;
|
||||
import org.apache.lucene.document.TextField;
|
||||
import org.apache.lucene.index.DirectoryReader;
|
||||
import org.apache.lucene.index.IndexWriter;
|
||||
import org.apache.lucene.index.IndexWriterConfig;
|
||||
import org.apache.lucene.index.StoredFields;
|
||||
import org.apache.lucene.index.Term;
|
||||
import org.apache.lucene.search.BooleanClause;
|
||||
import org.apache.lucene.search.BooleanQuery;
|
||||
import org.apache.lucene.search.BoostQuery;
|
||||
import org.apache.lucene.search.ConstantScoreQuery;
|
||||
import org.apache.lucene.search.FuzzyQuery;
|
||||
import org.apache.lucene.search.IndexSearcher;
|
||||
import org.apache.lucene.search.PhraseQuery;
|
||||
import org.apache.lucene.search.Query;
|
||||
import org.apache.lucene.search.ScoreDoc;
|
||||
import org.apache.lucene.search.TermQuery;
|
||||
import org.apache.lucene.search.TopDocs;
|
||||
import org.apache.lucene.search.uhighlight.DefaultPassageFormatter;
|
||||
import org.apache.lucene.search.uhighlight.UnifiedHighlighter;
|
||||
import org.apache.lucene.store.ByteBuffersDirectory;
|
||||
import org.apache.lucene.store.Directory;
|
||||
import org.apache.lucene.store.MMapDirectory;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
/**
|
||||
* A Lucene-backed {@link SiteSearchEngine} — the {@code search-lucene} plugin's contribution to the {@code search}
|
||||
* plugin's engine SPI. It builds a per-site full-text index over the search plugin's {@link SearchCorpus} — every
|
||||
* published page and content-source item (the entries plugins publish, …) the site has not excluded from search — indexing each
|
||||
* item's <b>title</b>,
|
||||
* <b>description</b> and <b>body text</b> (extracted from the item's indexable material with {@link HtmlText})
|
||||
* and answers a
|
||||
* query with a <b>tiered, constant-score</b> relevance model layered on top of Lucene's BM25 term matching:
|
||||
*
|
||||
* <ol>
|
||||
* <li><b>any-terms</b> — each analyzed query term as a {@code SHOULD} {@link TermQuery} across title (boosted),
|
||||
* description (boosted) and body, plus optional typo-tolerant {@link FuzzyQuery} clauses. This is the
|
||||
* BM25-scored base layer that separates documents <em>within</em> a tier.</li>
|
||||
* <li><b>near phrase (body)</b> — the query terms as a {@link PhraseQuery} with a small slop, a
|
||||
* {@code ConstantScoreQuery} worth {@code tierNearPhrase}: proximity beats scattered terms.</li>
|
||||
* <li><b>exact phrase (body)</b> — the query as an exact ({@code slop=0}) body phrase, worth
|
||||
* {@code tierPhraseBody}.</li>
|
||||
* <li><b>exact phrase (title)</b> — the query as an exact title phrase, worth {@code tierPhraseTitle}: a page
|
||||
* whose <em>title</em> is the query is the strongest possible match.</li>
|
||||
* <li><b>all-terms-anywhere</b> — a {@code ConstantScoreQuery} worth {@code tierAllTerms} that fires only when
|
||||
* every query term appears somewhere in the document, lifting complete matches above partial ones.</li>
|
||||
* </ol>
|
||||
*
|
||||
* <p>The tiers are additive {@code SHOULD} clauses, so a hit's score is the sum of the tiers it satisfies — an
|
||||
* exact-title-phrase hit outranks a near-phrase hit, which outranks a scattered-terms hit, deterministically.
|
||||
* Analysis (tokenization + <b>stemming</b>) is <b>per-locale</b> via {@link LocaleAnalyzers}, so a query matches
|
||||
* a stemmed surface form (an English query {@code running} matches {@code run}); the <em>same</em> analyzer is
|
||||
* used at index and query time so the two never drift. Result snippets are <b>query-focused and highlighted</b>:
|
||||
* {@link UnifiedHighlighter} wraps the matched terms in {@code <mark>…</mark>} within the best-matching body
|
||||
* passage, falling back to a plain leading snippet if highlighting yields nothing. Each hit also carries the words
|
||||
* the query matched as the page writes them ({@link MatchedForms}), which the page the result opens highlights.
|
||||
*
|
||||
* <p>The index covers the {@link SearchCorpus} the search plugin publishes — every published item, pages and
|
||||
* content-source items alike, minus the site's search exclusions. It is the same corpus the built-in engine
|
||||
* indexes, so what is searchable never depends on which engine serves the query, and the exclusion rule lives in
|
||||
* one place (the search plugin).
|
||||
*
|
||||
* <p><b>One index per language (since 3.2.0).</b> Each item is indexed once per language it exists in — its title,
|
||||
* description and body in that language (the body is the page as the kernel renders it there, bundle strings
|
||||
* included), linked at {@link CatalogEntry#pathFor} that language. A site has one index per language it speaks,
|
||||
* analyzed with that language's analyzer: the language's own documents plus, for an item that does not exist in
|
||||
* it, the item's <b>primary-locale</b> document (the site's default language when the item exists in it, else its
|
||||
* first language), so a page published in one language only is still found from every other. A query searches
|
||||
* the index of its own language ({@link SearchQuery#locale()}), with that index's analyzer; a language the site
|
||||
* does not speak searches the site default's. A fallback document is analyzed with the index's analyzer, not its
|
||||
* own language's — so it matches on exact and lightly stemmed forms, not on every inflection. Before 3.2.0 a site
|
||||
* had one index of primary-locale documents analyzed with the default language's analyzer, so every language
|
||||
* searched default-language text.
|
||||
*
|
||||
* <p>The index lives in heap ({@link ByteBuffersDirectory}) or on disk ({@link MMapDirectory}) per the app-level
|
||||
* {@link LuceneStorageProps}. It is cached per site, dropped by {@link #invalidate} — which the plugin's
|
||||
* {@code SiteEventListener} calls for every change that may reshape the corpus (a page write, a content source's
|
||||
* change, a site lifecycle event, any plugin's settings save) — rebuilt eagerly by the operator's {@link #reindex}
|
||||
* action, and additionally refreshed by a short TTL (the backstop for changes no event announces). The engine registers at {@link #priority()}
|
||||
* 100 (it supersedes the built-in engine) and is always {@link #available(String) available} — it builds on
|
||||
* demand. Per the SPI contract, {@link #search(SearchQuery)} <b>never throws</b>: any failure (I/O, a corrupt
|
||||
* index) is logged and returns no results.
|
||||
*/
|
||||
public class LuceneSearchEngine implements SiteSearchEngine, AutoCloseable {
|
||||
|
||||
static final String KEY = "search/lucene";
|
||||
private static final Logger log = LoggerFactory.getLogger(LuceneSearchEngine.class);
|
||||
|
||||
/** Indexed + query field names. */
|
||||
private static final String F_TITLE = "title";
|
||||
private static final String F_DESCRIPTION = "description";
|
||||
private static final String F_BODY = "body";
|
||||
/** Stored (display-only) field names. */
|
||||
private static final String S_URL = "s_url";
|
||||
private static final String S_TITLE = "s_title";
|
||||
private static final String S_DESCRIPTION = "s_description";
|
||||
private static final String S_BODY = "s_body";
|
||||
|
||||
private static final long FRESHNESS_MILLIS = 30_000L;
|
||||
private static final int SNIPPET_MAX = 200;
|
||||
private static final int MAX_QUERY_TERMS = 32;
|
||||
/** Slop for the "near phrase" tier — terms may be up to this far apart / lightly reordered. */
|
||||
private static final int NEAR_SLOP = 1;
|
||||
/** Private markers the {@link UnifiedHighlighter} wraps hits in; rewritten to {@code <mark>}/{@code </mark>}
|
||||
* only after the surrounding passage has been HTML-escaped, so a page's own {@code <} can't forge a tag. */
|
||||
private static final char MARK_OPEN_CH = '\u0001';
|
||||
private static final char MARK_CLOSE_CH = '\u0002';
|
||||
private static final String MARK_OPEN = String.valueOf(MARK_OPEN_CH);
|
||||
private static final String MARK_CLOSE = String.valueOf(MARK_CLOSE_CH);
|
||||
/** Guards the per-site subfolder used for a disk index (path-traversal / injection safe). */
|
||||
private static final Pattern SAFE_SITE_ID = Pattern.compile("[a-z0-9][a-z0-9._-]{0,63}");
|
||||
/** A language subdirectory name: an ISO 639 code as {@link Locale#getLanguage()} returns it. */
|
||||
private static final Pattern SAFE_LANGUAGE = Pattern.compile("[a-z]{2,8}");
|
||||
|
||||
private final SearchCorpus corpus;
|
||||
private final Sites sites;
|
||||
private final PluginSettings settings;
|
||||
private final LuceneStorageProps storage;
|
||||
private final LocaleAnalyzers analyzers = new LocaleAnalyzers();
|
||||
|
||||
private final Map<String, CachedIndex> cache = new ConcurrentHashMap<>();
|
||||
private final Map<String, Object> locks = new ConcurrentHashMap<>();
|
||||
/**
|
||||
* Bumped by every {@link #invalidate}. A build that started before an invalidation may have read the old corpus,
|
||||
* so it is kept only as already-stale: it answers the query that built it, and the next query rebuilds.
|
||||
*/
|
||||
private final AtomicLong generation = new AtomicLong();
|
||||
/** Site index folders already checked for a 3.1.x index (see {@link #deleteOldLayout}). */
|
||||
private final java.util.Set<Path> oldLayoutChecked = ConcurrentHashMap.newKeySet();
|
||||
/**
|
||||
* The sites whose index this thread is building. A build renders pages, and a page's widget that searched
|
||||
* the same site would re-enter the build (the per-site lock is reentrant) and recurse; such a search answers
|
||||
* nothing instead.
|
||||
*/
|
||||
private static final ThreadLocal<java.util.Set<String>> BUILDING = ThreadLocal.withInitial(java.util.HashSet::new);
|
||||
|
||||
/**
|
||||
* @param corpus what to index: the search plugin's corpus (the content listing minus the site's exclusions)
|
||||
* @param sites the kernel's site lookup (a site's default locale chooses the analyzer)
|
||||
* @param settings this plugin's per-site settings (the ranking knobs), read per query
|
||||
* @param storage the app-level storage settings (heap or disk)
|
||||
*/
|
||||
public LuceneSearchEngine(SearchCorpus corpus, Sites sites, PluginSettings settings, LuceneStorageProps storage) {
|
||||
this.corpus = Objects.requireNonNull(corpus, "corpus");
|
||||
this.sites = Objects.requireNonNull(sites, "sites");
|
||||
this.settings = Objects.requireNonNull(settings, "settings");
|
||||
this.storage = Objects.requireNonNull(storage, "storage");
|
||||
}
|
||||
|
||||
/** One language's index: its directory, the analyzer used to build it (reused at query time) and its size. */
|
||||
private record LanguageIndex(Directory dir, Analyzer analyzer, int documents) {
|
||||
}
|
||||
|
||||
/**
|
||||
* A built per-site index: one {@link LanguageIndex} per language the site speaks, the site default's language
|
||||
* (the index a query in another language searches), the number of items indexed, and when it was built.
|
||||
*/
|
||||
private record CachedIndex(Map<String, LanguageIndex> languages, String defaultLanguage, int items,
|
||||
long builtAtMillis) {
|
||||
|
||||
/** The same index, marked as already past its freshness window. */
|
||||
CachedIndex stale() {
|
||||
return new CachedIndex(languages, defaultLanguage, items, 0L);
|
||||
}
|
||||
|
||||
/** The index a query in {@code locale} searches; the site default's when the site lacks that language. */
|
||||
LanguageIndex forQuery(Locale locale) {
|
||||
LanguageIndex index = languages.get(locale.getLanguage());
|
||||
return index != null ? index : languages.get(defaultLanguage);
|
||||
}
|
||||
|
||||
void close() {
|
||||
languages.values().forEach(l -> closeQuietly(l.dir()));
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public String key() {
|
||||
return KEY;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int priority() {
|
||||
return 100; // supersede the built-in engine wherever this plugin is installed
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<SearchHit> search(SearchQuery query) {
|
||||
if (BUILDING.get().contains(query.siteId())) {
|
||||
return List.of(); // a search from inside this site's own index build (see BUILDING)
|
||||
}
|
||||
LanguageIndex index;
|
||||
try {
|
||||
index = index(query.siteId()).forQuery(query.locale());
|
||||
} catch (RuntimeException e) {
|
||||
log.warn("lucene index unavailable for site '{}': {}", query.siteId(), e.toString());
|
||||
return List.of();
|
||||
}
|
||||
if (index == null || index.documents() == 0) {
|
||||
return List.of();
|
||||
}
|
||||
List<String> terms = analyze(index.analyzer(), query.text());
|
||||
if (terms.isEmpty()) {
|
||||
return List.of();
|
||||
}
|
||||
RankingConfig ranking = ranking(query.siteId());
|
||||
Query q = buildQuery(terms, ranking);
|
||||
try (DirectoryReader reader = DirectoryReader.open(index.dir())) {
|
||||
IndexSearcher searcher = new IndexSearcher(reader);
|
||||
TopDocs top = searcher.search(q, Math.max(1, query.limit()));
|
||||
String[] highlights = highlight(searcher, index.analyzer(), q, top);
|
||||
StoredFields stored = searcher.storedFields();
|
||||
MatchedForms matched = MatchedForms.forQuery(index.analyzer(), terms, ranking.fuzzy());
|
||||
List<SearchHit> hits = new ArrayList<>(top.scoreDocs.length);
|
||||
for (int i = 0; i < top.scoreDocs.length; i++) {
|
||||
ScoreDoc sd = top.scoreDocs[i];
|
||||
Document d = stored.document(sd.doc);
|
||||
String snippet = snippet(highlights[i], d);
|
||||
List<String> forms = matched.in(
|
||||
List.of(nonNull(d.get(S_TITLE)), nonNull(d.get(S_DESCRIPTION)), nonNull(d.get(S_BODY))));
|
||||
hits.add(new SearchHit(d.get(S_URL), d.get(S_TITLE), snippet, sd.score, forms));
|
||||
}
|
||||
return List.copyOf(hits);
|
||||
} catch (IOException | RuntimeException e) {
|
||||
log.warn("lucene search failed for site '{}': {}", query.siteId(), e.toString());
|
||||
return List.of(); // an SPI never throws for a query; fall back to no results
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The SPI's manual-reindex hook: drops the cached index and rebuilds it <b>now</b> from current content,
|
||||
* returning the fresh document count — so the operator's reindex action rebuilds this engine too, not only
|
||||
* the built-in one. A failed rebuild logs and reports {@code 0}, per the SPI's never-throw posture.
|
||||
*/
|
||||
@Override
|
||||
public int reindex(String siteId) {
|
||||
corpus.refresh(siteId); // out-of-band edits fire no event; refresh the shared listing before rebuilding
|
||||
invalidate(siteId);
|
||||
return indexedDocuments(siteId);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------------------------------------- console
|
||||
|
||||
/**
|
||||
* The number of items (pages and content) currently in this site's index — items, not per-language documents
|
||||
* (builds/refreshes it if needed) — for the console.
|
||||
*/
|
||||
public int indexedDocuments(String siteId) {
|
||||
try {
|
||||
return index(siteId).items();
|
||||
} catch (RuntimeException e) {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
/** The effective per-tenant title boost (for the console). */
|
||||
public float effectiveTitleBoost(String siteId) {
|
||||
return ranking(siteId).titleBoost();
|
||||
}
|
||||
|
||||
/** The active storage mode ({@code heap}/{@code disk}) — for the console. */
|
||||
public String storageMode() {
|
||||
return storage.isDisk() ? "disk" : "heap";
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------------------------------- lifecycle
|
||||
|
||||
/**
|
||||
* Drops the site's cached index, so the next query rebuilds it from the current corpus. Called from the plugin's
|
||||
* {@code SiteEventListener} for every change that may reshape the corpus, after the kernel has evicted its own
|
||||
* caches — so the rebuild reads the new state.
|
||||
*/
|
||||
void invalidate(String siteId) {
|
||||
generation.incrementAndGet();
|
||||
evict(siteId);
|
||||
}
|
||||
|
||||
private void evict(String siteId) {
|
||||
CachedIndex removed = cache.remove(siteId);
|
||||
if (removed != null) {
|
||||
removed.close();
|
||||
}
|
||||
}
|
||||
|
||||
/** Release every cached directory and analyzer (Spring calls this on context shutdown). */
|
||||
@Override
|
||||
public void close() {
|
||||
cache.values().forEach(CachedIndex::close);
|
||||
cache.clear();
|
||||
analyzers.close();
|
||||
}
|
||||
|
||||
// --------------------------------------------------------------------------------------------- index build
|
||||
|
||||
private CachedIndex index(String siteId) {
|
||||
long now = System.currentTimeMillis();
|
||||
CachedIndex cached = cache.get(siteId);
|
||||
if (cached != null && now - cached.builtAtMillis() < FRESHNESS_MILLIS) {
|
||||
return cached;
|
||||
}
|
||||
synchronized (locks.computeIfAbsent(siteId, k -> new Object())) {
|
||||
cached = cache.get(siteId);
|
||||
if (cached != null && System.currentTimeMillis() - cached.builtAtMillis() < FRESHNESS_MILLIS) {
|
||||
return cached;
|
||||
}
|
||||
long started = generation.get();
|
||||
CachedIndex fresh;
|
||||
BUILDING.get().add(siteId);
|
||||
try {
|
||||
fresh = build(siteId);
|
||||
} finally {
|
||||
BUILDING.get().remove(siteId);
|
||||
}
|
||||
if (generation.get() != started) {
|
||||
fresh = fresh.stale(); // a change arrived mid-build: this one may hold the old corpus
|
||||
}
|
||||
CachedIndex prev = cache.put(siteId, fresh);
|
||||
if (prev != null) {
|
||||
prev.close();
|
||||
}
|
||||
return fresh;
|
||||
}
|
||||
}
|
||||
|
||||
/** One item's indexed fields in one language. */
|
||||
private record IndexedText(String url, String title, String description, String body) {
|
||||
}
|
||||
|
||||
/** An item's primary-locale fields and the languages it has its own documents in, while views are assembled. */
|
||||
private record Item(IndexedText primary, java.util.Set<String> languages) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds every language index of a site (see the class comment). Each item's text is read once per language it
|
||||
* exists in and reused by every index that holds it. An unknown site gets one empty index for English.
|
||||
*/
|
||||
private CachedIndex build(String siteId) {
|
||||
SiteView site = sites.find(siteId).orElse(null);
|
||||
Locale siteDefault = site == null ? Locale.ENGLISH : site.defaultLocale();
|
||||
Map<String, List<IndexedText>> own = new java.util.LinkedHashMap<>();
|
||||
List<Item> items = new ArrayList<>();
|
||||
try {
|
||||
for (CatalogEntry entry : corpus.corpus(siteId)) { // empty for an unknown site
|
||||
Locale primary = entry.ref().primaryLocale(siteDefault);
|
||||
java.util.Set<String> languages = new java.util.LinkedHashSet<>();
|
||||
IndexedText primaryText = null;
|
||||
List<Locale> locales = entry.ref().locales().isEmpty() ? List.of(siteDefault) : entry.ref().locales();
|
||||
for (Locale locale : locales) {
|
||||
if (!languages.add(locale.getLanguage())) {
|
||||
continue;
|
||||
}
|
||||
IndexedText text = text(siteId, entry, locale);
|
||||
own.computeIfAbsent(locale.getLanguage(), k -> new ArrayList<>()).add(text);
|
||||
if (locale.getLanguage().equals(primary.getLanguage())) {
|
||||
primaryText = text;
|
||||
}
|
||||
}
|
||||
items.add(new Item(primaryText != null ? primaryText : text(siteId, entry, primary),
|
||||
java.util.Set.copyOf(languages)));
|
||||
}
|
||||
} catch (RuntimeException e) {
|
||||
log.warn("lucene corpus read failed for site '{}': {}", siteId, e.toString());
|
||||
}
|
||||
java.util.Set<String> viewLanguages = new java.util.LinkedHashSet<>();
|
||||
viewLanguages.add(siteDefault.getLanguage());
|
||||
if (site != null) {
|
||||
site.locales().forEach(l -> viewLanguages.add(l.getLanguage()));
|
||||
}
|
||||
viewLanguages.addAll(own.keySet());
|
||||
Map<String, LanguageIndex> indexes = new java.util.HashMap<>();
|
||||
for (String language : viewLanguages) {
|
||||
List<IndexedText> view = new ArrayList<>(own.getOrDefault(language, List.of()));
|
||||
for (Item item : items) {
|
||||
if (!item.languages().contains(language)) {
|
||||
view.add(item.primary());
|
||||
}
|
||||
}
|
||||
indexes.put(language, write(siteId, language, view));
|
||||
}
|
||||
return new CachedIndex(Map.copyOf(indexes), siteDefault.getLanguage(), items.size(),
|
||||
System.currentTimeMillis());
|
||||
}
|
||||
|
||||
/** The item's fields in {@code locale}: title, description and body in that language, at its address there. */
|
||||
private IndexedText text(String siteId, CatalogEntry entry, Locale locale) {
|
||||
String title = localized(entry.ref().title(), locale, entry.ref().id());
|
||||
String description = localized(entry.ref().description(), locale, "");
|
||||
String body = HtmlText.toText(corpus.indexableText(siteId, entry, locale));
|
||||
return new IndexedText(entry.pathFor(locale), title, description, body);
|
||||
}
|
||||
|
||||
/** Writes one language's index with that language's analyzer; a failed write leaves what was added so far. */
|
||||
private LanguageIndex write(String siteId, String language, List<IndexedText> texts) {
|
||||
Analyzer analyzer = analyzers.forLanguage(language);
|
||||
Directory dir;
|
||||
try {
|
||||
dir = newDirectory(siteId, language);
|
||||
} catch (IOException e) {
|
||||
log.warn("lucene directory init failed for site '{}' ({}), falling back to heap: {}", siteId, language,
|
||||
e.toString());
|
||||
dir = new ByteBuffersDirectory();
|
||||
}
|
||||
int docs = 0;
|
||||
try (IndexWriter writer = new IndexWriter(dir, new IndexWriterConfig(analyzer))) {
|
||||
writer.deleteAll(); // rebuild-from-scratch semantics for a disk directory that already had content
|
||||
for (IndexedText text : texts) {
|
||||
Document doc = new Document();
|
||||
doc.add(new TextField(F_TITLE, text.title(), Field.Store.NO));
|
||||
doc.add(new TextField(F_DESCRIPTION, text.description(), Field.Store.NO));
|
||||
// Body is BOTH analyzed (for matching) and stored (so the highlighter can re-analyze the source).
|
||||
doc.add(new TextField(F_BODY, text.body(), Field.Store.YES));
|
||||
doc.add(new StoredField(S_URL, text.url()));
|
||||
doc.add(new StoredField(S_TITLE, text.title()));
|
||||
doc.add(new StoredField(S_DESCRIPTION, text.description()));
|
||||
doc.add(new StoredField(S_BODY, text.body()));
|
||||
writer.addDocument(doc);
|
||||
docs++;
|
||||
}
|
||||
} catch (IOException | RuntimeException e) {
|
||||
log.warn("lucene index build failed for site '{}' ({}): {}", siteId, language, e.toString());
|
||||
}
|
||||
return new LanguageIndex(dir, analyzer, docs);
|
||||
}
|
||||
|
||||
/**
|
||||
* A directory for one language of {@code siteId}: an in-memory {@link ByteBuffersDirectory} in heap mode, or a
|
||||
* memory-mapped {@link MMapDirectory} under {@code indexRoot/<siteId>/<language>} in disk mode. The site id is
|
||||
* validated against {@link #SAFE_SITE_ID}, the language against {@link #SAFE_LANGUAGE}, and the resolved path is
|
||||
* asserted to stay under the (normalized, absolute) index root, so a crafted id can never escape the index tree
|
||||
* — even though site ids are already path-safe upstream, storage paths get their own guard (defense in depth for
|
||||
* an operator-set root). Index files a 3.1.x build left directly under {@code indexRoot/<siteId>} (one index per
|
||||
* site) are deleted, so the old index does not linger beside the new ones.
|
||||
*/
|
||||
static boolean isLuceneFile(String name) {
|
||||
return name.startsWith(org.apache.lucene.index.IndexFileNames.SEGMENTS) || name.equals("write.lock")
|
||||
|| org.apache.lucene.index.IndexFileNames.CODEC_FILE_PATTERN.matcher(name).matches();
|
||||
}
|
||||
|
||||
private Directory newDirectory(String siteId, String language) throws IOException {
|
||||
if (!storage.isDisk()) {
|
||||
return new ByteBuffersDirectory();
|
||||
}
|
||||
if (!SAFE_SITE_ID.matcher(siteId).matches()) {
|
||||
throw new IOException("unsafe site id for a disk index: '" + siteId + "'");
|
||||
}
|
||||
if (!SAFE_LANGUAGE.matcher(language).matches()) {
|
||||
throw new IOException("unsafe language for a disk index: '" + language + "'");
|
||||
}
|
||||
Path root = Path.of(storage.getIndexRoot()).toAbsolutePath().normalize();
|
||||
Path siteDir = root.resolve(siteId).normalize();
|
||||
Path languageDir = siteDir.resolve(language).normalize();
|
||||
if (!languageDir.startsWith(root) || !languageDir.getParent().equals(siteDir)) {
|
||||
throw new IOException("index path escapes the index root: " + languageDir);
|
||||
}
|
||||
Files.createDirectories(languageDir);
|
||||
deleteOldLayout(siteDir);
|
||||
return new MMapDirectory(languageDir);
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes a 3.1.x single index left directly under a site's index directory — only files Lucene names
|
||||
* ({@code segments*}, {@code write.lock}, codec files such as {@code _0.cfs}), so an {@code indexRoot} pointed by
|
||||
* mistake at a folder holding other files loses none of them — once per site per process.
|
||||
*/
|
||||
private void deleteOldLayout(Path siteDir) {
|
||||
if (!oldLayoutChecked.add(siteDir)) {
|
||||
return;
|
||||
}
|
||||
try (java.util.stream.Stream<Path> files = Files.list(siteDir)) {
|
||||
files.filter(Files::isRegularFile).filter(f -> isLuceneFile(f.getFileName().toString())).forEach(file -> {
|
||||
try {
|
||||
Files.deleteIfExists(file);
|
||||
} catch (IOException ignored) {
|
||||
// a file that cannot be deleted is harmless: no index reads it any more
|
||||
}
|
||||
});
|
||||
} catch (IOException ignored) {
|
||||
// same: leftovers are never read
|
||||
}
|
||||
}
|
||||
|
||||
// --------------------------------------------------------------------------------------------- query build
|
||||
|
||||
/**
|
||||
* Composes the tiered constant-score query from the analyzed terms and the site's ranking config. See the
|
||||
* class doc for the tier semantics; the tiers are additive {@code SHOULD} clauses so a document's score is
|
||||
* the sum of the tiers it matches.
|
||||
*/
|
||||
Query buildQuery(List<String> terms, RankingConfig cfg) {
|
||||
BooleanQuery.Builder root = new BooleanQuery.Builder();
|
||||
|
||||
// Tier 1: any-terms (BM25-scored base) — each term across the three fields, with per-field boosts, plus
|
||||
// optional fuzzy variants. This layer separates documents WITHIN the higher constant-score tiers.
|
||||
BooleanQuery.Builder anyTerms = new BooleanQuery.Builder();
|
||||
for (String term : terms) {
|
||||
anyTerms.add(new BoostQuery(new TermQuery(new Term(F_TITLE, term)), cfg.titleBoost()),
|
||||
BooleanClause.Occur.SHOULD);
|
||||
anyTerms.add(new BoostQuery(new TermQuery(new Term(F_DESCRIPTION, term)), cfg.descriptionBoost()),
|
||||
BooleanClause.Occur.SHOULD);
|
||||
anyTerms.add(new TermQuery(new Term(F_BODY, term)), BooleanClause.Occur.SHOULD);
|
||||
if (cfg.fuzzy()) {
|
||||
int edits = maxEdits(term);
|
||||
if (edits > 0) {
|
||||
anyTerms.add(new BoostQuery(fuzzy(F_BODY, term, edits), cfg.fuzzyBoost()),
|
||||
BooleanClause.Occur.SHOULD);
|
||||
anyTerms.add(new BoostQuery(fuzzy(F_TITLE, term, edits), cfg.fuzzyBoost()),
|
||||
BooleanClause.Occur.SHOULD);
|
||||
}
|
||||
}
|
||||
}
|
||||
root.add(anyTerms.build(), BooleanClause.Occur.SHOULD);
|
||||
|
||||
// Tiers 2–4: phrase tiers (only meaningful for a multi-term query; a single term IS its own phrase, so
|
||||
// the phrase tiers would just double-count — skip them for one term).
|
||||
if (terms.size() > 1) {
|
||||
root.add(constant(phrase(F_TITLE, terms, 0), cfg.tierPhraseTitle()), BooleanClause.Occur.SHOULD);
|
||||
root.add(constant(phrase(F_BODY, terms, 0), cfg.tierPhraseBody()), BooleanClause.Occur.SHOULD);
|
||||
root.add(constant(phrase(F_BODY, terms, NEAR_SLOP), cfg.tierNearPhrase()), BooleanClause.Occur.SHOULD);
|
||||
}
|
||||
|
||||
// Tier 5: all-terms-anywhere — every term must appear in some field; a constant lift for complete matches.
|
||||
root.add(constant(allTermsAnywhere(terms), cfg.tierAllTerms()), BooleanClause.Occur.SHOULD);
|
||||
|
||||
return root.build();
|
||||
}
|
||||
|
||||
/** Wraps {@code q} so it contributes a flat, position-independent {@code score} (the tier's constant). */
|
||||
private static Query constant(Query q, float score) {
|
||||
return new BoostQuery(new ConstantScoreQuery(q), score);
|
||||
}
|
||||
|
||||
/** A {@link PhraseQuery} over {@code field} for the ordered {@code terms}, allowing {@code slop} reordering. */
|
||||
private static Query phrase(String field, List<String> terms, int slop) {
|
||||
PhraseQuery.Builder b = new PhraseQuery.Builder().setSlop(slop);
|
||||
for (String term : terms) {
|
||||
b.add(new Term(field, term));
|
||||
}
|
||||
return b.build();
|
||||
}
|
||||
|
||||
/** A {@code MUST}-across-fields query: every term must match in title, description or body (in any position). */
|
||||
private static Query allTermsAnywhere(List<String> terms) {
|
||||
BooleanQuery.Builder all = new BooleanQuery.Builder();
|
||||
for (String term : terms) {
|
||||
BooleanQuery.Builder anyField = new BooleanQuery.Builder();
|
||||
anyField.add(new TermQuery(new Term(F_TITLE, term)), BooleanClause.Occur.SHOULD);
|
||||
anyField.add(new TermQuery(new Term(F_DESCRIPTION, term)), BooleanClause.Occur.SHOULD);
|
||||
anyField.add(new TermQuery(new Term(F_BODY, term)), BooleanClause.Occur.SHOULD);
|
||||
all.add(anyField.build(), BooleanClause.Occur.MUST);
|
||||
}
|
||||
return all.build();
|
||||
}
|
||||
|
||||
/** A typo-tolerant {@link FuzzyQuery}: {@code edits} max, 1-char prefix fixed, 50 expansions, transpositions. */
|
||||
private static FuzzyQuery fuzzy(String field, String term, int edits) {
|
||||
return new FuzzyQuery(new Term(field, term), edits, 1, 50, true);
|
||||
}
|
||||
|
||||
/** The Levenshtein edit budget for a term: none for very short terms, 1 for short, 2 for longer — so a fuzzy
|
||||
* match never turns a 3-letter word into an unrelated one. */
|
||||
static int maxEdits(String term) {
|
||||
int len = term.length();
|
||||
if (len <= 2) {
|
||||
return 0;
|
||||
}
|
||||
return (len <= 5) ? 1 : 2;
|
||||
}
|
||||
|
||||
// --------------------------------------------------------------------------------------------- highlighting
|
||||
|
||||
/**
|
||||
* Query-focused highlighting over the stored body field: {@link UnifiedHighlighter} finds the best passage
|
||||
* for each top doc and wraps the matched terms in the private markers (rewritten to {@code <mark>} later).
|
||||
* Returns one snippet per top doc (aligned by index), each possibly {@code null} when the doc has no
|
||||
* highlightable body. Any highlighter failure degrades to an all-{@code null} array — the caller then falls
|
||||
* back to a plain leading snippet, so highlighting never breaks a search.
|
||||
*/
|
||||
private static String[] highlight(IndexSearcher searcher, Analyzer analyzer, Query query, TopDocs top) {
|
||||
if (top.scoreDocs.length == 0) {
|
||||
return new String[0];
|
||||
}
|
||||
try {
|
||||
UnifiedHighlighter highlighter = UnifiedHighlighter.builder(searcher, analyzer)
|
||||
.withFormatter(new DefaultPassageFormatter(MARK_OPEN, MARK_CLOSE, " … ", false))
|
||||
.build();
|
||||
return highlighter.highlight(F_BODY, query, top, 1);
|
||||
} catch (IOException | RuntimeException e) {
|
||||
log.debug("lucene highlighting failed, falling back to plain snippets: {}", e.toString());
|
||||
return new String[top.scoreDocs.length];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The snippet for a hit: prefer the highlighter's query-focused, {@code <mark>}-wrapped passage; if there is
|
||||
* none, fall back to the page description, else a leading slice of the body — always plain (no markers). The
|
||||
* highlighted passage is produced by first HTML-escaping the raw passage, THEN turning the private markers
|
||||
* into real {@code <mark>} tags, so page content can never inject markup while the highlight tags survive.
|
||||
*/
|
||||
private static String snippet(String highlighted, Document doc) {
|
||||
if (highlighted != null && (highlighted.indexOf(MARK_OPEN_CH) >= 0)) {
|
||||
return markup(highlighted);
|
||||
}
|
||||
String description = doc.get(S_DESCRIPTION);
|
||||
String base = (description != null && !description.isBlank()) ? description : doc.get(S_BODY);
|
||||
if (base == null || base.isBlank()) {
|
||||
return "";
|
||||
}
|
||||
base = base.strip();
|
||||
return base.length() <= SNIPPET_MAX ? base : base.substring(0, SNIPPET_MAX).stripTrailing() + "…";
|
||||
}
|
||||
|
||||
/** Escapes the passage's HTML metacharacters, then rewrites the private markers to {@code <mark>} tags. */
|
||||
private static String markup(String passage) {
|
||||
String escaped = passage.replace("&", "&").replace("<", "<").replace(">", ">")
|
||||
.replace("\"", """).replace("'", "'");
|
||||
return escaped.replace(MARK_OPEN, "<mark>").replace(MARK_CLOSE, "</mark>").strip();
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------------------------------- shared
|
||||
|
||||
/** Analyzes free text into its terms with {@code analyzer} (same transform used at index time), capped. */
|
||||
private static List<String> analyze(Analyzer analyzer, String text) {
|
||||
List<String> out = new ArrayList<>();
|
||||
try (TokenStream ts = analyzer.tokenStream(F_BODY, text)) {
|
||||
CharTermAttribute term = ts.addAttribute(CharTermAttribute.class);
|
||||
ts.reset();
|
||||
while (ts.incrementToken() && out.size() < MAX_QUERY_TERMS) {
|
||||
out.add(term.toString());
|
||||
}
|
||||
ts.end();
|
||||
} catch (IOException e) {
|
||||
return List.of();
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** This plugin's ranking knobs for the site, from its per-site settings (declared defaults applied). */
|
||||
private RankingConfig ranking(String siteId) {
|
||||
return RankingConfig.from(settings.site(siteId).values());
|
||||
}
|
||||
|
||||
/** A map value for {@code locale}'s language, else any present value, else {@code fallback}. */
|
||||
private static String localized(Map<String, String> byLocale, Locale locale, String fallback) {
|
||||
String v = byLocale.get(locale.getLanguage());
|
||||
if (v == null || v.isBlank()) {
|
||||
v = byLocale.values().stream().filter(x -> x != null && !x.isBlank()).findFirst().orElse(null);
|
||||
}
|
||||
return (v == null || v.isBlank()) ? fallback : v;
|
||||
}
|
||||
|
||||
private static String nonNull(String value) {
|
||||
return value == null ? "" : value;
|
||||
}
|
||||
|
||||
private static void closeQuietly(Directory dir) {
|
||||
try {
|
||||
dir.close();
|
||||
} catch (IOException | UncheckedIOException e) {
|
||||
log.debug("failed to close a lucene directory: {}", e.toString());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package mx.quest.searchlucene;
|
||||
|
||||
import java.util.Objects;
|
||||
import mx.quest.runway.spi.model.CatalogChange;
|
||||
import mx.quest.runway.spi.service.SiteEventListener;
|
||||
|
||||
/**
|
||||
* The plugin's one {@link SiteEventListener}, a {@link Phase#CONSUMER CONSUMER}: it reads the content listing (through
|
||||
* the search plugin's {@code SearchCorpus}) and contributes none. The kernel delivers it after every kernel cache the
|
||||
* change affects has been evicted and every content source has dropped its own state, so the rebuild it triggers reads
|
||||
* the new state.
|
||||
*
|
||||
* <p>{@link #onCatalogChanged} drops the site's index for <b>every</b> cause — a page write, a content source's change,
|
||||
* a site lifecycle event, and <b>any</b> plugin's settings save: a source reshapes its items from its settings (its
|
||||
* URL prefix, say), and the search plugin's {@code exclude} list reshapes the corpus. No {@code pluginId} scoping is
|
||||
* needed. This plugin's own settings (the ranking knobs) are read per query, so they need nothing here. The callback
|
||||
* only evicts; the rebuild happens lazily on the next query. It runs on every node, for local and replayed changes
|
||||
* alike: it only drops local state.
|
||||
*/
|
||||
final class LuceneSiteEvents implements SiteEventListener {
|
||||
|
||||
private final LuceneSearchEngine engine;
|
||||
|
||||
LuceneSiteEvents(LuceneSearchEngine engine) {
|
||||
this.engine = Objects.requireNonNull(engine, "engine");
|
||||
}
|
||||
|
||||
@Override
|
||||
public Phase phase() {
|
||||
return Phase.CONSUMER;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onCatalogChanged(CatalogChange change) {
|
||||
engine.invalidate(change.siteId());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
package mx.quest.searchlucene;
|
||||
|
||||
import java.util.Locale;
|
||||
|
||||
/**
|
||||
* The plugin's <b>app-level</b> settings — where the index bytes live — bound from
|
||||
* {@code external/plugin-settings/search-lucene.yml} (keys under {@code runway.plugin.search-lucene.*}), the
|
||||
* plugin.yml {@code settings:} schema. Storage is a <b>platform</b> concern, not a tenant one: a filesystem path
|
||||
* a tenant could edit would be an isolation/abuse risk, so it is app-level and applied on <b>restart</b> (a
|
||||
* plugin reads its app-level settings through its own {@code @ConfigurationProperties}, never host machinery). The
|
||||
* binding is declared on the {@code @Bean} method ({@code searchLuceneStorageProps} in {@link SearchLuceneConfig}), so
|
||||
* the bean carries the plugin-id prefix every plugin bean name needs.
|
||||
*
|
||||
* <p>Field defaults mirror the schema defaults, so the plugin behaves sensibly (heap storage) when the file is
|
||||
* absent — degrade-don't-crash.
|
||||
*
|
||||
* @see Storage the two storage modes and their trade-offs
|
||||
*/
|
||||
public class LuceneStorageProps {
|
||||
|
||||
/**
|
||||
* Where a per-site Lucene index is held.
|
||||
*
|
||||
* <ul>
|
||||
* <li>{@link #HEAP} — an in-memory {@code ByteBuffersDirectory}: no disk footprint, but the index is
|
||||
* rebuilt from the page store after every restart. The default; ideal for small/medium sites.</li>
|
||||
* <li>{@link #DISK} — a memory-mapped {@code MMapDirectory} under {@link #getIndexRoot()}{@code /<siteId>}:
|
||||
* survives restarts and lets the OS page large indexes in/out of memory. Choose for large corpora.</li>
|
||||
* </ul>
|
||||
*/
|
||||
public enum Storage { HEAP, DISK }
|
||||
|
||||
private Storage storage = Storage.HEAP;
|
||||
private String indexRoot = "./external/plugins/search-lucene/index";
|
||||
|
||||
/** The configured storage mode; never {@code null} (defaults to {@link Storage#HEAP}). */
|
||||
public Storage getStorage() {
|
||||
return storage;
|
||||
}
|
||||
|
||||
/**
|
||||
* Binds the {@code storage} setting. Tolerant of case and blanks: an unrecognized or blank value falls back
|
||||
* to {@link Storage#HEAP} rather than failing the context (degrade-don't-crash for a hand-edited file).
|
||||
*/
|
||||
public void setStorage(String storage) {
|
||||
if (storage == null || storage.isBlank()) {
|
||||
this.storage = Storage.HEAP;
|
||||
return;
|
||||
}
|
||||
try {
|
||||
this.storage = Storage.valueOf(storage.trim().toUpperCase(Locale.ROOT));
|
||||
} catch (IllegalArgumentException ex) {
|
||||
this.storage = Storage.HEAP;
|
||||
}
|
||||
}
|
||||
|
||||
/** The root folder for disk indexes (per-site subfolders are created under it); never blank. */
|
||||
public String getIndexRoot() {
|
||||
return indexRoot;
|
||||
}
|
||||
|
||||
/** Binds the {@code indexRoot} setting; a blank value restores the default so the path is never empty. */
|
||||
public void setIndexRoot(String indexRoot) {
|
||||
this.indexRoot = (indexRoot == null || indexRoot.isBlank())
|
||||
? "./external/plugins/search-lucene/index" : indexRoot.trim();
|
||||
}
|
||||
|
||||
/** Whether disk (MMap) storage is selected. */
|
||||
public boolean isDisk() {
|
||||
return storage == Storage.DISK;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,128 @@
|
||||
package mx.quest.searchlucene;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashSet;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Set;
|
||||
import mx.quest.search.spi.SearchHit;
|
||||
import org.apache.lucene.analysis.Analyzer;
|
||||
import org.apache.lucene.analysis.TokenStream;
|
||||
import org.apache.lucene.analysis.tokenattributes.CharTermAttribute;
|
||||
import org.apache.lucene.analysis.tokenattributes.OffsetAttribute;
|
||||
import org.apache.lucene.search.FuzzyQuery;
|
||||
import org.apache.lucene.util.automaton.ByteRunnable;
|
||||
import org.apache.lucene.util.automaton.CompiledAutomaton;
|
||||
|
||||
/**
|
||||
* The words a query matched in one document, as they are written there, for {@link SearchHit#terms()}: the page a
|
||||
* result opens highlights these, so they must be the <em>surface</em> forms, not the analyzed terms. The query
|
||||
* {@code maestría} is the term {@code maestr} after Spanish stemming; the page says {@code maestrías}, and that is
|
||||
* the word to highlight.
|
||||
*
|
||||
* <p>Each stored text (title, description, body) is run through the same analyzer as the index, and a token whose
|
||||
* term is a query term is kept with the characters its offsets point at. When the site has typo tolerance on, a
|
||||
* token within the query's fuzzy edit distance of a term counts too, by the same rule as the fuzzy clauses
|
||||
* ({@link LuceneSearchEngine#maxEdits}, a one-character fixed prefix, transpositions). The fuzzy clauses expand to at
|
||||
* most 50 index terms, so on a large site a word within the distance may be highlighted although it did not add to
|
||||
* the score; it is still a word the query nearly spelled.
|
||||
*
|
||||
* <p>Bounded: at most {@link SearchHit#MAX_TERMS} forms, and only the first {@value #MAX_SCAN_CHARS} characters of
|
||||
* a text are read, so a very long page costs a fixed amount per hit. Any analysis failure returns what was found.
|
||||
*/
|
||||
final class MatchedForms {
|
||||
|
||||
/** Characters of one text read per hit; the forms of a real page appear well before this. */
|
||||
static final int MAX_SCAN_CHARS = 64 * 1024;
|
||||
|
||||
private final Analyzer analyzer;
|
||||
private final Set<String> exact;
|
||||
private final List<ByteRunnable> near;
|
||||
|
||||
private MatchedForms(Analyzer analyzer, List<String> terms, boolean fuzzy) {
|
||||
this.analyzer = analyzer;
|
||||
this.exact = new HashSet<>(terms);
|
||||
this.near = fuzzy ? automata(terms) : List.of();
|
||||
}
|
||||
|
||||
/**
|
||||
* The matcher for one query, built once and used for every hit: the fuzzy automata cost about half a millisecond
|
||||
* per term to build, so building them per hit made a long query over many hits cost seconds of CPU.
|
||||
*
|
||||
* @param analyzer the analyzer the index was built with
|
||||
* @param terms the analyzed query terms
|
||||
* @param fuzzy whether the site's ranking adds fuzzy clauses
|
||||
*/
|
||||
static MatchedForms forQuery(Analyzer analyzer, List<String> terms, boolean fuzzy) {
|
||||
return new MatchedForms(analyzer, terms, fuzzy);
|
||||
}
|
||||
|
||||
/** The forms found in one hit's stored texts, the most visible first (title, description, body). */
|
||||
List<String> in(List<String> texts) {
|
||||
Set<String> forms = new LinkedHashSet<>();
|
||||
for (String text : texts) {
|
||||
if (text == null || text.isBlank()) {
|
||||
continue;
|
||||
}
|
||||
collect(analyzer, text.length() > MAX_SCAN_CHARS ? text.substring(0, MAX_SCAN_CHARS) : text,
|
||||
exact, near, forms);
|
||||
if (forms.size() >= SearchHit.MAX_TERMS) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
return List.copyOf(forms);
|
||||
}
|
||||
|
||||
private static List<ByteRunnable> automata(List<String> terms) {
|
||||
List<ByteRunnable> out = new ArrayList<>();
|
||||
for (String term : terms) {
|
||||
int edits = LuceneSearchEngine.maxEdits(term);
|
||||
if (edits > 0) {
|
||||
CompiledAutomaton automaton = FuzzyQuery.getFuzzyAutomaton(term, edits, 1, true);
|
||||
ByteRunnable runnable = automaton.getByteRunnable();
|
||||
if (runnable != null) {
|
||||
out.add(runnable);
|
||||
}
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
private static void collect(Analyzer analyzer, String text, Set<String> exact, List<ByteRunnable> near,
|
||||
Set<String> forms) {
|
||||
try (TokenStream ts = analyzer.tokenStream("body", text)) {
|
||||
CharTermAttribute term = ts.addAttribute(CharTermAttribute.class);
|
||||
OffsetAttribute offset = ts.addAttribute(OffsetAttribute.class);
|
||||
ts.reset();
|
||||
while (ts.incrementToken() && forms.size() < SearchHit.MAX_TERMS) {
|
||||
String t = term.toString();
|
||||
if (exact.contains(t) || accepted(near, t)) {
|
||||
int start = offset.startOffset();
|
||||
int end = offset.endOffset();
|
||||
if (start >= 0 && end <= text.length() && start < end) {
|
||||
forms.add(text.substring(start, end).toLowerCase(Locale.ROOT));
|
||||
}
|
||||
}
|
||||
}
|
||||
ts.end();
|
||||
} catch (IOException | RuntimeException e) {
|
||||
// Highlighting is a convenience: keep what was found rather than fail the search.
|
||||
}
|
||||
}
|
||||
|
||||
private static boolean accepted(List<ByteRunnable> near, String term) {
|
||||
if (near.isEmpty()) {
|
||||
return false;
|
||||
}
|
||||
byte[] bytes = term.getBytes(StandardCharsets.UTF_8);
|
||||
for (ByteRunnable automaton : near) {
|
||||
if (automaton.run(bytes, 0, bytes.length)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
package mx.quest.searchlucene;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* The per-tenant ranking tuning for one site, resolved from the plugin's per-site settings
|
||||
* ({@code sites/<id>/plugins/search-lucene.yml}, read live per query through the SPI's {@code PluginSettings}, which
|
||||
* applies the descriptor's declared defaults under the stored values). It
|
||||
* carries the ~8 knobs the {@code siteSettings:} schema exposes; each is read defensively (a missing, blank, or
|
||||
* malformed value falls back to the historical default, and every value is clamped to a sane range) so a
|
||||
* hand-edited or partial file can never produce a broken query — <b>degrade-don't-crash</b>.
|
||||
*
|
||||
* <p>All values are resolved <b>once per query</b> in {@link #from(Map)} and then used as plain immutable data by
|
||||
* the query builder — the config map is never touched during query construction.
|
||||
*
|
||||
* @param fuzzy whether typo-tolerant {@code FuzzyQuery} clauses are added (default {@code true})
|
||||
* @param fuzzyBoost weight of a fuzzy term match relative to an exact one (default {@code 0.4})
|
||||
* @param titleBoost term-match boost on the title field in the any-terms tier (default {@code 8.0})
|
||||
* @param descriptionBoost term-match boost on the description field in the any-terms tier (default {@code 4.0})
|
||||
* @param tierPhraseTitle constant score for an exact query phrase found in the title (default {@code 4000})
|
||||
* @param tierPhraseBody constant score for an exact query phrase found in the body (default {@code 2000})
|
||||
* @param tierNearPhrase constant score for a near (slop=1) query phrase in the body (default {@code 800})
|
||||
* @param tierAllTerms constant score for a document containing all query terms anywhere (default {@code 300})
|
||||
*/
|
||||
record RankingConfig(boolean fuzzy, float fuzzyBoost, float titleBoost, float descriptionBoost,
|
||||
float tierPhraseTitle, float tierPhraseBody, float tierNearPhrase, float tierAllTerms) {
|
||||
|
||||
static final boolean DEF_FUZZY = true;
|
||||
static final float DEF_FUZZY_BOOST = 0.4f;
|
||||
static final float DEF_TITLE_BOOST = 8.0f;
|
||||
static final float DEF_DESCRIPTION_BOOST = 4.0f;
|
||||
static final float DEF_TIER_PHRASE_TITLE = 4000f;
|
||||
static final float DEF_TIER_PHRASE_BODY = 2000f;
|
||||
static final float DEF_TIER_NEAR_PHRASE = 800f;
|
||||
static final float DEF_TIER_ALL_TERMS = 300f;
|
||||
|
||||
/** Upper bound applied to every boost/tier score — generous, but stops a fat-fingered value from overflowing
|
||||
* the score math or drowning every other signal. */
|
||||
private static final float MAX = 1_000_000f;
|
||||
|
||||
/** The historical defaults — used when a site has no per-tenant config at all (or an empty map). */
|
||||
static RankingConfig defaults() {
|
||||
return from(Map.of());
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolves the ranking config from a site's plugin config map. Each knob is read with
|
||||
* {@link #decimal}/{@link #flag}, which coerce {@link Number}/{@link String} values, ignore blanks and
|
||||
* garbage, and fall back to the default; boosts and tier scores are clamped to {@code [0, MAX]}.
|
||||
*
|
||||
* @param cfg the effective per-tenant values ({@code SettingsView.values()}; may be empty; never {@code null})
|
||||
*/
|
||||
static RankingConfig from(Map<String, Object> cfg) {
|
||||
return new RankingConfig(
|
||||
flag(cfg, "fuzzy", DEF_FUZZY),
|
||||
decimal(cfg, "fuzzyBoost", DEF_FUZZY_BOOST),
|
||||
decimal(cfg, "titleBoost", DEF_TITLE_BOOST),
|
||||
decimal(cfg, "descriptionBoost", DEF_DESCRIPTION_BOOST),
|
||||
decimal(cfg, "tierPhraseTitle", DEF_TIER_PHRASE_TITLE),
|
||||
decimal(cfg, "tierPhraseBody", DEF_TIER_PHRASE_BODY),
|
||||
decimal(cfg, "tierNearPhrase", DEF_TIER_NEAR_PHRASE),
|
||||
decimal(cfg, "tierAllTerms", DEF_TIER_ALL_TERMS));
|
||||
}
|
||||
|
||||
/** Reads a non-negative decimal knob, clamped to {@code [0, MAX]}; missing/blank/garbage ⇒ {@code def}. */
|
||||
private static float decimal(Map<String, Object> cfg, String key, float def) {
|
||||
Object v = cfg.get(key);
|
||||
float raw;
|
||||
if (v instanceof Number n) {
|
||||
raw = n.floatValue();
|
||||
} else if (v instanceof String s && !s.isBlank()) {
|
||||
try {
|
||||
raw = Float.parseFloat(s.trim());
|
||||
} catch (NumberFormatException ex) {
|
||||
return def;
|
||||
}
|
||||
} else {
|
||||
return def;
|
||||
}
|
||||
if (Float.isNaN(raw) || Float.isInfinite(raw)) {
|
||||
return def;
|
||||
}
|
||||
return Math.max(0f, Math.min(MAX, raw));
|
||||
}
|
||||
|
||||
/** Reads a boolean knob; accepts {@link Boolean} and the strings true/on/yes/1 (case-insensitive). */
|
||||
private static boolean flag(Map<String, Object> cfg, String key, boolean def) {
|
||||
Object v = cfg.get(key);
|
||||
if (v instanceof Boolean b) {
|
||||
return b;
|
||||
}
|
||||
if (v instanceof String s && !s.isBlank()) {
|
||||
String t = s.trim().toLowerCase(java.util.Locale.ROOT);
|
||||
return t.equals("true") || t.equals("on") || t.equals("yes") || t.equals("1");
|
||||
}
|
||||
return def;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
package mx.quest.searchlucene;
|
||||
|
||||
import mx.quest.runway.spi.service.PluginSettings;
|
||||
import mx.quest.runway.spi.service.SiteEventListener;
|
||||
import mx.quest.runway.spi.service.Sites;
|
||||
import mx.quest.search.spi.SearchCorpus;
|
||||
import mx.quest.search.spi.SiteSearchEngine;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
/**
|
||||
* The plugin's {@code mainClass} — the single {@code @Configuration} the host registers into its context before
|
||||
* refresh. Every bean is wired EXPLICITLY (no {@code @ComponentScan}); the package {@code mx.quest.searchlucene} lives
|
||||
* OUTSIDE {@code mx.quest.runway} so the host never double-scans it.
|
||||
*
|
||||
* <p><b>SPI only.</b> Everything this plugin needs arrives as a published service: {@link PluginSettings} (this
|
||||
* plugin's per-site ranking knobs, bound to this plugin by the jar this class was loaded from) and {@link Sites} (a
|
||||
* site's default locale) from the kernel's SPI 0.6.0, and {@link SearchCorpus} (what to index — the content listing
|
||||
* minus the site's search exclusions) from the {@code search} plugin's own SPI (search 2.0.0). Nothing outside
|
||||
* {@code mx.quest.runway.spi} and {@code mx.quest.search.spi} is linked. Every bean name starts with the plugin id in
|
||||
* lowerCamelCase ({@code searchLucene…}), the kernel's rule for the bean namespace plugins share.
|
||||
*
|
||||
* <p>{@code requires: search >= 2.0.0} and {@code requires: lucene-provider == 10.4.0} in {@code plugin.yml} are HARD
|
||||
* gates: without the search plugin (which publishes {@link SiteSearchEngine} and {@link SearchCorpus}) or the
|
||||
* provider (which supplies the exact Lucene binaries) this plugin is not loaded — so both are present at wire time.
|
||||
*
|
||||
* <p>App-level storage settings bind from {@code external/plugin-settings/search-lucene.yml} into
|
||||
* {@link LuceneStorageProps} through the {@code @ConfigurationProperties} on {@link #searchLuceneStorageProps()} —
|
||||
* not {@code @EnableConfigurationProperties}, which would name the bean {@code runway.plugin.search-lucene-…} and break
|
||||
* the bean-name rule.
|
||||
*/
|
||||
@Configuration(proxyBeanMethods = false)
|
||||
public class SearchLuceneConfig {
|
||||
|
||||
/** The app-level settings ({@code runway.plugin.search-lucene.*}: storage, indexRoot), applied on restart. */
|
||||
@Bean
|
||||
@ConfigurationProperties(prefix = "runway.plugin.search-lucene")
|
||||
public LuceneStorageProps searchLuceneStorageProps() {
|
||||
return new LuceneStorageProps();
|
||||
}
|
||||
|
||||
/**
|
||||
* The engine, registered as its concrete type — which IS-A {@link SiteSearchEngine}, so the search plugin's
|
||||
* {@code List<SiteSearchEngine>} collects it (one definition, no duplicate; NEVER {@code @Primary}), while the
|
||||
* admin model and the listener inject the concrete type. Spring closes the engine's cached Lucene directories on
|
||||
* shutdown through {@code destroyMethod}.
|
||||
*/
|
||||
@Bean(destroyMethod = "close")
|
||||
public LuceneSearchEngine searchLuceneEngine(SearchCorpus corpus, Sites sites, PluginSettings settings,
|
||||
LuceneStorageProps storage) {
|
||||
return new LuceneSearchEngine(corpus, sites, settings, storage);
|
||||
}
|
||||
|
||||
/** Drops a site's index on every change that may reshape what it holds (a CONSUMER listener). */
|
||||
@Bean
|
||||
public SiteEventListener searchLuceneSiteEvents(LuceneSearchEngine engine) {
|
||||
return new LuceneSiteEvents(engine);
|
||||
}
|
||||
|
||||
/** Read-only status for the dashboard card and the admin fragment ({@code @searchLuceneAdminModel}). */
|
||||
@Bean
|
||||
public LuceneAdminModel searchLuceneAdminModel(LuceneSearchEngine engine) {
|
||||
return new LuceneAdminModel(engine);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,243 @@
|
||||
package mx.quest.searchlucene;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import mx.quest.runway.spi.model.CatalogEntry;
|
||||
import mx.quest.runway.spi.model.ContentRef;
|
||||
import mx.quest.runway.spi.model.LocalizedUrl;
|
||||
import mx.quest.runway.spi.model.SiteView;
|
||||
import mx.quest.runway.spi.testkit.FakeContentCatalog;
|
||||
import mx.quest.runway.spi.testkit.FakePluginSettings;
|
||||
import mx.quest.runway.spi.testkit.FakeSiteServices;
|
||||
import mx.quest.search.SiteSearchCorpus;
|
||||
import mx.quest.search.spi.SearchCorpus;
|
||||
import mx.quest.search.spi.SearchHit;
|
||||
import mx.quest.search.spi.SearchQuery;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
|
||||
/**
|
||||
* One index per language (3.2.0): each item is indexed in every language it exists in, with that language's
|
||||
* analyzer, and a query searches its own language's index — plus the primary-locale document of an item missing
|
||||
* from that language. The corpus answers each language's own body, as the kernel does since 1.0.0-rc6 (a page's
|
||||
* copy comes from the site's bundles in the requested language).
|
||||
*/
|
||||
class LucenePerLanguageTest {
|
||||
|
||||
private static final String SITE = "acme";
|
||||
private static final Locale EN = Locale.ENGLISH;
|
||||
private static final Locale ES = Locale.of("es");
|
||||
private static final Locale FR = Locale.FRENCH;
|
||||
|
||||
private FakeContentCatalog catalog;
|
||||
private FakePluginSettings searchSettings;
|
||||
private FakeSiteServices sites;
|
||||
private LuceneStorageProps storage;
|
||||
private LuceneSearchEngine engine;
|
||||
private Map<String, Map<String, String>> bodies = Map.of();
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
catalog = new FakeContentCatalog().site(SITE);
|
||||
searchSettings = new FakePluginSettings();
|
||||
sites = new FakeSiteServices().site(new SiteView(SITE, "Acme", EN, List.of(EN, ES, FR), null));
|
||||
storage = new LuceneStorageProps();
|
||||
newEngine();
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void tearDown() {
|
||||
engine.close();
|
||||
}
|
||||
|
||||
private void newEngine() {
|
||||
if (engine != null) {
|
||||
engine.close();
|
||||
}
|
||||
SearchCorpus base = new SiteSearchCorpus(catalog, searchSettings);
|
||||
SearchCorpus perLanguage = new SearchCorpus() {
|
||||
@Override
|
||||
public List<CatalogEntry> corpus(String siteId) {
|
||||
return base.corpus(siteId);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String indexableText(String siteId, CatalogEntry entry, Locale locale) {
|
||||
return bodies.getOrDefault(entry.ref().id(), Map.of()).getOrDefault(locale.getLanguage(), "");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void refresh(String siteId) {
|
||||
base.refresh(siteId);
|
||||
}
|
||||
};
|
||||
engine = new LuceneSearchEngine(perLanguage, sites, new FakePluginSettings(), storage);
|
||||
}
|
||||
|
||||
private static CatalogEntry about() {
|
||||
ContentRef ref = new ContentRef("about", "/about", Map.of("es", "/acerca", "fr", "/a-propos"),
|
||||
List.of(EN, ES, FR), Map.of("en", "About", "es", "Acerca", "fr", "À propos"), Map.of(), "", "tpl",
|
||||
true, Instant.EPOCH, false, null, null, Map.of());
|
||||
return new CatalogEntry("pages", ref, List.of(new LocalizedUrl(EN, "/about", null),
|
||||
new LocalizedUrl(ES, "/es/acerca", null), new LocalizedUrl(FR, "/fr/a-propos", null)), "/about");
|
||||
}
|
||||
|
||||
private static CatalogEntry englishOnly() {
|
||||
ContentRef ref = new ContentRef("news", "/news", Map.of(), List.of(EN), Map.of("en", "News"), Map.of(), "",
|
||||
"tpl", true, Instant.EPOCH, false, null, null, Map.of());
|
||||
return new CatalogEntry("pages", ref, List.of(new LocalizedUrl(EN, "/news", null)), "/news");
|
||||
}
|
||||
|
||||
private void corpus(CatalogEntry... entries) {
|
||||
catalog.clear(SITE);
|
||||
for (CatalogEntry e : entries) {
|
||||
catalog.entry(SITE, e);
|
||||
}
|
||||
}
|
||||
|
||||
private List<SearchHit> search(String q, Locale locale) {
|
||||
return engine.search(new SearchQuery(SITE, q, locale, 20));
|
||||
}
|
||||
|
||||
private void trilingualAbout() {
|
||||
bodies = Map.of("about", Map.of(
|
||||
"en", "<p>A roastery that stays up late, roasting every night.</p>",
|
||||
"es", "<p>Una tostaduría que trasnocha. Nuestros alumnos aprenden con una facultad de excelencia.</p>",
|
||||
"fr", "<p>Une torréfaction nocturne.</p>"));
|
||||
corpus(about());
|
||||
}
|
||||
|
||||
@Test
|
||||
void eachLanguageSearchesItsOwnIndexAtItsOwnAddress() {
|
||||
trilingualAbout();
|
||||
List<SearchHit> es = search("trasnocha", ES);
|
||||
assertEquals(1, es.size(), "the Spanish text is searchable from a Spanish results page");
|
||||
assertEquals("/es/acerca", es.get(0).url());
|
||||
assertEquals("Acerca", es.get(0).title());
|
||||
assertTrue(es.get(0).snippet().contains("<mark>"), es.get(0).snippet());
|
||||
|
||||
assertTrue(search("trasnocha", EN).isEmpty(), "English searches the English index only");
|
||||
assertTrue(search("roastery", ES).isEmpty(), "Spanish searches the Spanish index only");
|
||||
assertEquals("/about", search("roastery", EN).get(0).url());
|
||||
}
|
||||
|
||||
@Test
|
||||
void eachIndexUsesItsLanguagesAnalyzer() {
|
||||
trilingualAbout();
|
||||
// French light stemming folds the accent: an unaccented query finds the accented word.
|
||||
List<SearchHit> fr = search("torrefaction", FR);
|
||||
assertEquals(1, fr.size(), "the French analyzer matches 'torrefaction' to 'torréfaction'");
|
||||
assertEquals("/fr/a-propos", fr.get(0).url());
|
||||
// Spanish stemming: an inflected form finds the page.
|
||||
assertEquals(1, search("facultades", ES).size(), "the Spanish analyzer stems 'facultades' to 'facultad'");
|
||||
assertEquals(1, search("roasted", EN).size(), "the English analyzer stems 'roasted' to 'roast'");
|
||||
}
|
||||
|
||||
@Test
|
||||
void theMatchedFormsAreTheTargetLanguagesWords() {
|
||||
trilingualAbout();
|
||||
List<SearchHit> hits = search("facultades", ES);
|
||||
assertEquals(1, hits.size());
|
||||
assertTrue(hits.get(0).terms().contains("facultad"), () -> "terms: " + hits.get(0).terms());
|
||||
}
|
||||
|
||||
@Test
|
||||
void anItemMissingFromTheQueryLanguageIsFoundInItsPrimaryLanguage() {
|
||||
bodies = Map.of("about", Map.of("es", "<p>tostaduría</p>"), "news", Map.of("en", "<p>harvest report</p>"));
|
||||
corpus(about(), englishOnly());
|
||||
List<SearchHit> hits = search("harvest", ES);
|
||||
assertEquals(1, hits.size(), "a page the site publishes in English only is still found from Spanish");
|
||||
assertEquals("/news", hits.get(0).url());
|
||||
assertEquals(1, search("tostaduría", ES).size());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aLanguageTheSiteDoesNotSpeakSearchesTheDefaultLanguage() {
|
||||
trilingualAbout();
|
||||
List<SearchHit> hits = search("roastery", Locale.GERMAN);
|
||||
assertEquals(1, hits.size());
|
||||
assertEquals("/about", hits.get(0).url());
|
||||
}
|
||||
|
||||
@Test
|
||||
void theConsoleCountsItemsNotLanguages() {
|
||||
trilingualAbout();
|
||||
corpus(about(), englishOnly());
|
||||
assertEquals(2, engine.indexedDocuments(SITE));
|
||||
assertEquals(2, engine.reindex(SITE));
|
||||
}
|
||||
|
||||
@Test
|
||||
void onDiskEachLanguageHasItsOwnFolderAndTheOldSingleIndexIsRemoved(@TempDir Path tmp) throws IOException {
|
||||
Path siteDir = tmp.resolve(SITE);
|
||||
Files.createDirectories(siteDir);
|
||||
Files.writeString(siteDir.resolve("segments_1"), "a 3.1.x index file"); // the old one-index-per-site layout
|
||||
Files.writeString(siteDir.resolve("_0.cfs"), "a 3.1.x codec file");
|
||||
Files.writeString(siteDir.resolve("notes.txt"), "not Lucene's"); // indexRoot pointed at the wrong folder
|
||||
storage.setStorage("disk");
|
||||
storage.setIndexRoot(tmp.toString());
|
||||
newEngine();
|
||||
trilingualAbout();
|
||||
|
||||
assertEquals("/es/acerca", search("trasnocha", ES).get(0).url());
|
||||
for (String language : List.of("en", "es", "fr")) {
|
||||
assertTrue(Files.isDirectory(siteDir.resolve(language)), "a folder for " + language);
|
||||
}
|
||||
assertFalse(Files.exists(siteDir.resolve("segments_1")), "the 3.1.x index file is deleted");
|
||||
assertFalse(Files.exists(siteDir.resolve("_0.cfs")), "…and its codec files");
|
||||
assertTrue(Files.exists(siteDir.resolve("notes.txt")), "a file Lucene did not name is never deleted");
|
||||
}
|
||||
|
||||
@Test
|
||||
void onlyLuceneFileNamesCountAsAnOldIndex() {
|
||||
for (String name : List.of("segments_1", "segments_a", "segments.gen", "write.lock", "_0.cfs", "_0.si",
|
||||
"_1_Lucene90_0.dvd")) {
|
||||
assertTrue(LuceneSearchEngine.isLuceneFile(name), name);
|
||||
}
|
||||
for (String name : List.of("site.yml", "notes.txt", "messages.properties", "index.html")) {
|
||||
assertFalse(LuceneSearchEngine.isLuceneFile(name), name);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void aSearchFromInsideTheSitesOwnIndexBuildAnswersNothingInsteadOfRecursing() {
|
||||
bodies = Map.of();
|
||||
corpus(about());
|
||||
engine.close();
|
||||
SearchCorpus base = new SiteSearchCorpus(catalog, searchSettings);
|
||||
LuceneSearchEngine[] self = new LuceneSearchEngine[1];
|
||||
java.util.concurrent.atomic.AtomicInteger inner = new java.util.concurrent.atomic.AtomicInteger(-1);
|
||||
SearchCorpus reentrant = new SearchCorpus() { // a page whose widget searches while it is being rendered
|
||||
@Override
|
||||
public List<CatalogEntry> corpus(String siteId) {
|
||||
return base.corpus(siteId);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String indexableText(String siteId, CatalogEntry entry, Locale locale) {
|
||||
inner.set(self[0].search(new SearchQuery(SITE, "roastery", locale, 5)).size());
|
||||
return "<p>roastery</p>";
|
||||
}
|
||||
|
||||
@Override
|
||||
public void refresh(String siteId) {
|
||||
base.refresh(siteId);
|
||||
}
|
||||
};
|
||||
engine = new LuceneSearchEngine(reentrant, sites, new FakePluginSettings(), storage);
|
||||
self[0] = engine;
|
||||
assertEquals(1, search("roastery", EN).size(), "the outer search is answered");
|
||||
assertEquals(0, inner.get(), "the search from inside the build answered nothing (and did not recurse)");
|
||||
}
|
||||
}
|
||||
+668
@@ -0,0 +1,668 @@
|
||||
package mx.quest.searchlucene;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
import mx.quest.runway.spi.model.CatalogChange;
|
||||
import mx.quest.runway.spi.model.CatalogEntry;
|
||||
import mx.quest.runway.spi.model.ContentRef;
|
||||
import mx.quest.runway.spi.model.LocalizedUrl;
|
||||
import mx.quest.runway.spi.model.SiteLifecycleEvent;
|
||||
import mx.quest.runway.spi.model.SiteView;
|
||||
import mx.quest.runway.spi.testkit.EventDispatch;
|
||||
import mx.quest.runway.spi.testkit.FakeContentCatalog;
|
||||
import mx.quest.runway.spi.testkit.FakePluginSettings;
|
||||
import mx.quest.runway.spi.testkit.FakeSiteServices;
|
||||
import mx.quest.search.SiteSearchCorpus;
|
||||
import mx.quest.search.spi.SearchCorpus;
|
||||
import mx.quest.search.spi.SearchHit;
|
||||
import mx.quest.search.spi.SearchQuery;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
|
||||
/**
|
||||
* The Lucene engine: tiered constant-score ranking (exact phrase > near > scattered), fuzzy matching,
|
||||
* per-locale stemming analyzers, heap and disk storage, {@code <mark>} highlighting, the 8 per-tenant tuning knobs
|
||||
* (read per query through {@code PluginSettings}), the index's freshness (the plugin's {@code SiteEventListener}, the
|
||||
* reindex hook) and the {@code SiteSearchEngine} SPI contract (never throws, empty index ⇒ no results, limit honored).
|
||||
*
|
||||
* <p>The corpus is the search plugin's own {@link SiteSearchCorpus} (search 2.0.0) over the testkit's
|
||||
* {@link FakeContentCatalog}, with the search plugin's settings in a second {@link FakePluginSettings} — so the
|
||||
* exclusion rule exercised here is the one the search plugin applies on a real deployment, not a copy of it.
|
||||
*/
|
||||
class LuceneSearchEngineTest {
|
||||
|
||||
private static final String SITE = "acme";
|
||||
|
||||
private FakeContentCatalog catalog;
|
||||
private FakePluginSettings searchSettings;
|
||||
private FakePluginSettings luceneSettings;
|
||||
private FakeSiteServices sites;
|
||||
private SearchCorpus corpus;
|
||||
private LuceneStorageProps storage;
|
||||
private LuceneSearchEngine engine;
|
||||
|
||||
// ------------------------------------------------------------------------------------------------ fixtures
|
||||
|
||||
/** A published English page (source {@code pages}, id = slug) at {@code /<id>}. */
|
||||
static CatalogEntry item(String id, String title, String description) {
|
||||
return item("pages", id, "en", title, description);
|
||||
}
|
||||
|
||||
/** A published item of {@code source}, available in {@code lang} only, at {@code /<id>}. */
|
||||
static CatalogEntry item(String source, String id, String lang, String title, String description) {
|
||||
Locale locale = Locale.forLanguageTag(lang);
|
||||
ContentRef ref = new ContentRef(id, "/" + id, Map.of(), List.of(locale), Map.of(lang, title),
|
||||
Map.of(lang, description), "", "tpl", true, Instant.EPOCH, false, null, null, Map.of());
|
||||
return new CatalogEntry(source, ref, List.of(new LocalizedUrl(locale, "/" + id, null)), null);
|
||||
}
|
||||
|
||||
private void site(String id, Locale defaultLocale) {
|
||||
sites.site(new SiteView(id, id, defaultLocale, List.of(defaultLocale), null));
|
||||
catalog.site(id);
|
||||
}
|
||||
|
||||
/** Replaces the site's listing. */
|
||||
private void corpus(String siteId, CatalogEntry... items) {
|
||||
catalog.clear(siteId);
|
||||
for (CatalogEntry item : items) {
|
||||
catalog.entry(siteId, item);
|
||||
}
|
||||
}
|
||||
|
||||
private void corpus(CatalogEntry... items) {
|
||||
corpus(SITE, items);
|
||||
}
|
||||
|
||||
/** The item's raw indexable material — what the catalog's {@code indexableText} answers for it. */
|
||||
private void body(CatalogEntry item, String html) {
|
||||
catalog.text(SITE, item.compositeId(), html);
|
||||
}
|
||||
|
||||
private void newEngine() {
|
||||
if (engine != null) {
|
||||
engine.close();
|
||||
}
|
||||
engine = new LuceneSearchEngine(corpus, sites, luceneSettings, storage);
|
||||
}
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
catalog = new FakeContentCatalog();
|
||||
searchSettings = new FakePluginSettings();
|
||||
luceneSettings = new FakePluginSettings();
|
||||
sites = new FakeSiteServices();
|
||||
corpus = new SiteSearchCorpus(catalog, searchSettings);
|
||||
storage = new LuceneStorageProps(); // heap by default
|
||||
site(SITE, Locale.ENGLISH);
|
||||
newEngine();
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void tearDown() {
|
||||
engine.close();
|
||||
}
|
||||
|
||||
private List<SearchHit> search(String q, int limit) {
|
||||
return engine.search(new SearchQuery(SITE, q, Locale.ENGLISH, limit));
|
||||
}
|
||||
|
||||
private static List<String> urls(List<SearchHit> hits) {
|
||||
return hits.stream().map(SearchHit::url).toList();
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------------------------------ SPI contract
|
||||
|
||||
@Test
|
||||
void keyPriorityAndAvailability() {
|
||||
assertEquals("search/lucene", engine.key());
|
||||
assertEquals(100, engine.priority(), "outranks the built-in engine");
|
||||
assertTrue(engine.available(SITE), "always available — builds on demand");
|
||||
}
|
||||
|
||||
@Test
|
||||
void emptyIndexReturnsNoResultsAndNeverThrows() {
|
||||
assertTrue(search("anything", 20).isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aCorpusFailureDegradesToNoResultsRatherThanThrowing() {
|
||||
// The corpus blowing up must not propagate out of search() — the SPI never throws for a query.
|
||||
SearchCorpus failing = new SearchCorpus() {
|
||||
@Override
|
||||
public List<CatalogEntry> corpus(String siteId) {
|
||||
throw new IllegalStateException("catalog down");
|
||||
}
|
||||
|
||||
@Override
|
||||
public String indexableText(String siteId, CatalogEntry entry, Locale locale) {
|
||||
throw new IllegalStateException("catalog down");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void refresh(String siteId) {
|
||||
throw new IllegalStateException("catalog down");
|
||||
}
|
||||
};
|
||||
try (LuceneSearchEngine broken = new LuceneSearchEngine(failing, sites, luceneSettings, storage)) {
|
||||
assertTrue(broken.search(new SearchQuery(SITE, "runway", Locale.ENGLISH, 20)).isEmpty(),
|
||||
"a failure returns no results, not an exception");
|
||||
assertEquals(0, broken.indexedDocuments(SITE));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void anUnsafeOrUnknownSiteAnswersNothingAndNeverThrows() {
|
||||
corpus(item("guide", "Runway Guide", ""));
|
||||
assertTrue(engine.search(new SearchQuery("../etc", "runway", Locale.ENGLISH, 20)).isEmpty(),
|
||||
"an unsafe site id is refused by the services; the engine answers no results");
|
||||
assertEquals(0, engine.indexedDocuments("../etc"));
|
||||
assertTrue(engine.search(new SearchQuery("ghost", "runway", Locale.ENGLISH, 20)).isEmpty(),
|
||||
"an unknown site has an empty index");
|
||||
assertEquals(0, engine.reindex("ghost"));
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------------- matched words (since 3.1.0)
|
||||
|
||||
@Test
|
||||
void aHitCarriesTheSurfaceFormsTheStemmedQueryMatched() {
|
||||
site("es-site", Locale.forLanguageTag("es"));
|
||||
CatalogEntry mba = item("pages", "mba", "es", "Maestrías ejecutivas", "");
|
||||
corpus("es-site", mba, item("pages", "otra", "es", "Contacto", ""));
|
||||
catalog.text("es-site", mba.compositeId(), "<p>Nuestra maestría dura dos años.</p>");
|
||||
List<SearchHit> hits = engine.search(new SearchQuery("es-site", "maestría", Locale.forLanguageTag("es"), 10));
|
||||
assertEquals(List.of("/mba"), urls(hits));
|
||||
assertEquals(List.of("maestrías", "maestría"), hits.get(0).terms(),
|
||||
"the words as the page writes them, title first, so the target page can highlight them");
|
||||
}
|
||||
|
||||
@Test
|
||||
void stopWordsOfTheQueryAreNotReported() {
|
||||
CatalogEntry guide = item("guide", "The Guide", "");
|
||||
corpus(guide);
|
||||
body(guide, "<p>The art of the deployment.</p>");
|
||||
List<SearchHit> hits = search("the deployment", 10);
|
||||
assertEquals(List.of("deployment"), hits.get(0).terms(), "'the' is a stop word: it matched nothing");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aTypoToleratedMatchReportsTheWordItFound() {
|
||||
CatalogEntry guide = item("guide", "Guide", "");
|
||||
corpus(guide);
|
||||
body(guide, "<p>A small framework.</p>");
|
||||
List<SearchHit> hits = search("framewrok", 10);
|
||||
assertEquals(List.of("/guide"), urls(hits), "fuzzy matching is on by default");
|
||||
assertEquals(List.of("framework"), hits.get(0).terms(), "the page's own spelling is the word to highlight");
|
||||
}
|
||||
|
||||
@Test
|
||||
void typoToleranceDecidesWhetherNearTermsAreReported() {
|
||||
CatalogEntry guide = item("guide", "Guide", "");
|
||||
corpus(guide);
|
||||
body(guide, "<p>Deploy the deployment; deployer.</p>");
|
||||
// English stemming: deployment and deployer are "deploy", while deploy itself is "deploi", one edit away.
|
||||
assertEquals(List.of("deploy", "deployment", "deployer"), search("deployment", 10).get(0).terms(),
|
||||
"fuzzy on (the default): the near term is a match, so its word is reported");
|
||||
luceneSettings.site(SITE, Map.of("fuzzy", false));
|
||||
assertEquals(List.of("deployment", "deployer"), search("deployment", 10).get(0).terms(),
|
||||
"fuzzy off: only the words whose stem is the query's");
|
||||
}
|
||||
|
||||
@Test
|
||||
void matchesTitleAndLinksToThePage() {
|
||||
corpus(item("guide", "Runway Guide", "How to deploy."),
|
||||
item("about", "About", "Our team."));
|
||||
List<SearchHit> hits = search("runway", 20);
|
||||
assertEquals(1, hits.size());
|
||||
assertEquals("Runway Guide", hits.get(0).title());
|
||||
assertEquals("/guide", hits.get(0).url(), "the hit links to the URL the kernel computed for the entry");
|
||||
}
|
||||
|
||||
@Test
|
||||
void matchesBodyTextNotJustMetadata() {
|
||||
CatalogEntry post = item("post", "Weekly Notes", "News.");
|
||||
corpus(post);
|
||||
body(post, "<h1>Weekly Notes</h1><p>We shipped the new <b>lucene</b> engine.</p>");
|
||||
List<SearchHit> hits = search("lucene", 20);
|
||||
assertEquals(1, hits.size(), "a body-only term matches — full-text, not metadata-only");
|
||||
assertEquals("Weekly Notes", hits.get(0).title());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aContentSourceItemIsIndexedAlongsidePages() {
|
||||
// A blog entry (any content source's item) enters the SAME Lucene index as pages — same corpus, same
|
||||
// tiers, no engine-side special case.
|
||||
CatalogEntry entry = item("blog", "hello-world", "en", "Hello World", "The first entry.");
|
||||
corpus(item("guide", "Runway Guide", "Deploy runway."), entry);
|
||||
body(entry, "Runway makes multi-tenant hosting simple.");
|
||||
List<SearchHit> hits = search("runway", 20);
|
||||
assertEquals(2, hits.size(), "the blog entry and the page are both indexed");
|
||||
assertTrue(urls(hits).contains("/hello-world"), "the entry's hit links to the entry's own URL");
|
||||
}
|
||||
|
||||
@Test
|
||||
void analysisIsTokenizedAndCaseInsensitive() {
|
||||
corpus(item("p", "The Runway Platform", ""));
|
||||
assertFalse(search("RUNWAY", 20).isEmpty(), "matching is case-insensitive (analyzed)");
|
||||
assertFalse(search("platform runway", 20).isEmpty(), "multi-term matches");
|
||||
}
|
||||
|
||||
@Test
|
||||
void nonMatchesReturnNothing() {
|
||||
corpus(item("live", "Contact", "reach us"));
|
||||
assertTrue(search("runway", 20).isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void theSearchPluginsExclusionsReachTheIndexThroughItsCorpus() {
|
||||
// The exclude list is the SEARCH plugin's per-site setting, applied by its SearchCorpus — this engine never
|
||||
// reads it. "/Privacy" exercises the tolerated leading slash and the case fold; "hello-world" matches a
|
||||
// content-source item's own id, so it drops the blog entry too.
|
||||
searchSettings.site(SITE, Map.of("exclude", List.of("/Privacy", "hello-world")));
|
||||
CatalogEntry privacy = item("privacy", "Privacy", "Runway privacy policy.");
|
||||
corpus(privacy, item("guide", "Runway Guide", "Deploy runway."),
|
||||
item("blog", "hello-world", "en", "Runway Hello", "About runway."));
|
||||
body(privacy, "runway runway runway");
|
||||
List<SearchHit> hits = search("runway", 20);
|
||||
assertEquals(List.of("/guide"), urls(hits),
|
||||
"the excluded page AND the excluded source item are left out of the index");
|
||||
assertEquals(1, engine.indexedDocuments(SITE));
|
||||
}
|
||||
|
||||
@Test
|
||||
void theLimitIsHonored() {
|
||||
corpus(item("a", "Runway A", ""), item("b", "Runway B", ""), item("c", "Runway C", ""));
|
||||
assertEquals(2, search("runway", 2).size());
|
||||
}
|
||||
|
||||
@Test
|
||||
void equalScoresKeepTheCorpusOrder() {
|
||||
// Lucene breaks a score tie by document number, i.e. the order the corpus listed the entries in.
|
||||
corpus(item("c", "Runway", ""), item("a", "Runway", ""), item("b", "Runway", ""));
|
||||
assertEquals(List.of("/c", "/a", "/b"), urls(search("runway", 20)));
|
||||
}
|
||||
|
||||
// --------------------------------------------------------------------------------------- locale and URL
|
||||
|
||||
@Test
|
||||
void anItemMissingFromTheSiteDefaultLanguageIsIndexedAndLinkedInItsOwnLanguage() {
|
||||
// A Spanish-only entry on an English site: its title, body and URL are its Spanish ones (CatalogEntry.pathFor
|
||||
// its primary locale) — never an unprefixed default-language path, which 404s for such an item.
|
||||
ContentRef ref = new ContentRef("receta", "/receta", Map.of("es", "/es/receta"), List.of(Locale.forLanguageTag("es")),
|
||||
Map.of("es", "Receta de tamales"), Map.of("es", "Cocina"), "", "tpl", true, Instant.EPOCH, false,
|
||||
null, null, Map.of());
|
||||
CatalogEntry spanish = new CatalogEntry("blog", ref,
|
||||
List.of(new LocalizedUrl(Locale.forLanguageTag("es"), "/es/receta", null)), null);
|
||||
corpus(spanish);
|
||||
catalog.text(SITE, spanish.compositeId(), "<p>tamales verdes</p>");
|
||||
List<SearchHit> hits = search("tamales", 20);
|
||||
assertEquals(1, hits.size());
|
||||
assertEquals("/es/receta", hits.get(0).url(), "linked at the item's real (Spanish) address");
|
||||
assertEquals("Receta de tamales", hits.get(0).title());
|
||||
}
|
||||
|
||||
@Test
|
||||
void anItemWithoutATitleIsShownUnderItsId() {
|
||||
ContentRef ref = new ContentRef("untitled-note", "/untitled-note", Map.of(), List.of(Locale.ENGLISH), Map.of(),
|
||||
Map.of(), "", "tpl", true, Instant.EPOCH, false, null, null, Map.of());
|
||||
CatalogEntry untitled = new CatalogEntry("blog", ref,
|
||||
List.of(new LocalizedUrl(Locale.ENGLISH, "/untitled-note", null)), null);
|
||||
corpus(untitled);
|
||||
body(untitled, "<p>zeppelin</p>");
|
||||
assertEquals("untitled-note", search("zeppelin", 20).get(0).title());
|
||||
}
|
||||
|
||||
@Test
|
||||
void theIndexableTextIsAskedForInTheItemsPrimaryLocale() {
|
||||
List<Locale> asked = new ArrayList<>();
|
||||
SearchCorpus recording = new SearchCorpus() {
|
||||
@Override
|
||||
public List<CatalogEntry> corpus(String siteId) {
|
||||
return List.of(item("guide", "Guide", ""), item("blog", "nota", "es", "Nota", ""));
|
||||
}
|
||||
|
||||
@Override
|
||||
public String indexableText(String siteId, CatalogEntry entry, Locale locale) {
|
||||
asked.add(locale);
|
||||
return "";
|
||||
}
|
||||
|
||||
@Override
|
||||
public void refresh(String siteId) {
|
||||
}
|
||||
};
|
||||
try (LuceneSearchEngine e = new LuceneSearchEngine(recording, sites, luceneSettings, storage)) {
|
||||
assertEquals(2, e.indexedDocuments(SITE));
|
||||
}
|
||||
assertEquals(List.of(Locale.ENGLISH, Locale.forLanguageTag("es")), asked,
|
||||
"the site default for an item that has it, else the item's own first language");
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------------------------- index freshness
|
||||
|
||||
@Test
|
||||
void reindexRefreshesTheListingAndRebuildsFromCurrentContentImmediately() {
|
||||
corpus(item("a", "Runway", ""));
|
||||
assertEquals(1, engine.indexedDocuments(SITE));
|
||||
// The corpus grows; the cached index (fresh for 30 s) would still report 1 until reindex.
|
||||
corpus(item("a", "Runway", ""), item("b", "Runway Two", ""));
|
||||
assertEquals(1, engine.indexedDocuments(SITE), "the cached index still serves inside the TTL");
|
||||
assertEquals(2, engine.reindex(SITE),
|
||||
"the SPI reindex hook drops the cache and rebuilds NOW, returning the fresh count");
|
||||
assertEquals(List.of(SITE), catalog.refreshed(),
|
||||
"…after refreshing the shared listing through the corpus (out-of-band edits announce nothing)");
|
||||
}
|
||||
|
||||
/** Proves that delivering {@code deliver} drops the cached index: before it the old index serves. */
|
||||
private void assertTheIndexIsDroppedBy(Runnable deliver) {
|
||||
corpus(item("a", "Runway", ""));
|
||||
assertEquals(1, search("runway", 20).size());
|
||||
corpus(item("a", "Runway", ""), item("b", "Runway Two", ""));
|
||||
assertEquals(1, search("runway", 20).size(), "before any change the cached index still serves");
|
||||
deliver.run();
|
||||
assertEquals(2, search("runway", 20).size(), "the change drops the index; the next query rebuilds");
|
||||
}
|
||||
|
||||
private EventDispatch events() {
|
||||
return new EventDispatch("search-lucene", Set.of()).listener(new LuceneSiteEvents(engine));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aPageChangeDropsTheSiteIndex() {
|
||||
EventDispatch events = events();
|
||||
assertTheIndexIsDroppedBy(() -> events.page(SITE, "b", List.of(),
|
||||
List.of(new LocalizedUrl(Locale.ENGLISH, "/b", null))));
|
||||
assertTrue(events.failures().isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aContentSourceChangeDropsTheSiteIndex() {
|
||||
EventDispatch events = events();
|
||||
assertTheIndexIsDroppedBy(() -> events.catalog(new CatalogChange(SITE, CatalogChange.Cause.CONTENT, "blog",
|
||||
"second", "blog", List.of(), List.of(), true)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void anotherPluginsSettingsSaveDropsTheSiteIndex() {
|
||||
// Any plugin's settings may reshape the corpus — the blog's prefix, the search plugin's exclude list — so
|
||||
// a SETTINGS change of a plugin other than this one drops the index too (no pluginId scoping).
|
||||
EventDispatch events = events();
|
||||
assertTheIndexIsDroppedBy(() -> events.settings(SITE, "search"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aSiteLifecycleEventDropsTheSiteIndex() {
|
||||
EventDispatch events = events();
|
||||
assertTheIndexIsDroppedBy(() -> events.lifecycle(SITE, SiteLifecycleEvent.Kind.RESTORED, true));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aReplayedChangeFromAnotherNodeDropsTheLocalIndexToo() {
|
||||
EventDispatch events = events();
|
||||
assertTheIndexIsDroppedBy(() -> events.catalog(new CatalogChange(SITE, CatalogChange.Cause.PAGE, "pages",
|
||||
"b", null, List.of(), List.of(), false)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aChangeOnAnotherSiteLeavesThisSitesIndexAlone() {
|
||||
corpus(item("a", "Runway", ""));
|
||||
assertEquals(1, search("runway", 20).size());
|
||||
corpus(item("a", "Runway", ""), item("b", "Runway Two", ""));
|
||||
events().page("other", "x", List.of(), List.of());
|
||||
assertEquals(1, search("runway", 20).size(), "only the changed site's index is dropped");
|
||||
}
|
||||
|
||||
@Test
|
||||
void theListenerIsAConsumer() {
|
||||
assertEquals(LuceneSiteEvents.Phase.CONSUMER, new LuceneSiteEvents(engine).phase(),
|
||||
"it reads the listing after every source has dropped its state");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aChangeThatArrivesWhileTheIndexIsBeingBuiltIsNotLostToTheTtl() {
|
||||
// A change announced while a build is reading the corpus: the build may hold the old corpus, so it must not be
|
||||
// cached as fresh for 30 s — the next query rebuilds.
|
||||
AtomicBoolean changeMidBuild = new AtomicBoolean(true);
|
||||
List<List<CatalogEntry>> listings = new ArrayList<>(List.of(
|
||||
List.of(item("a", "Runway", "")),
|
||||
List.of(item("a", "Runway", ""), item("b", "Runway Two", ""))));
|
||||
LuceneSearchEngine[] self = new LuceneSearchEngine[1];
|
||||
SearchCorpus racing = new SearchCorpus() {
|
||||
@Override
|
||||
public List<CatalogEntry> corpus(String siteId) {
|
||||
List<CatalogEntry> current = listings.size() > 1 ? listings.remove(0) : listings.get(0);
|
||||
if (changeMidBuild.getAndSet(false)) {
|
||||
self[0].invalidate(siteId); // the listener runs on another thread in real life
|
||||
}
|
||||
return current;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String indexableText(String siteId, CatalogEntry entry, Locale locale) {
|
||||
return "";
|
||||
}
|
||||
|
||||
@Override
|
||||
public void refresh(String siteId) {
|
||||
}
|
||||
};
|
||||
try (LuceneSearchEngine e = new LuceneSearchEngine(racing, sites, luceneSettings, storage)) {
|
||||
self[0] = e;
|
||||
assertEquals(1, e.search(new SearchQuery(SITE, "runway", Locale.ENGLISH, 20)).size(),
|
||||
"the query that built the index is answered from it");
|
||||
assertEquals(2, e.search(new SearchQuery(SITE, "runway", Locale.ENGLISH, 20)).size(),
|
||||
"the next query rebuilds, because a change arrived during the first build");
|
||||
assertEquals(2, e.search(new SearchQuery(SITE, "runway", Locale.ENGLISH, 20)).size());
|
||||
}
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------------------------------------- tiering
|
||||
|
||||
@Test
|
||||
void exactPhraseHitOutranksScatteredTermsHit() {
|
||||
CatalogEntry scattered = item("scattered", "Notes", "");
|
||||
CatalogEntry exact = item("exact", "Manual", "");
|
||||
corpus(scattered, exact);
|
||||
body(exact, "<p>The cloud deployment guide explains everything.</p>");
|
||||
body(scattered, "<p>cloud infrastructure. a long unrelated paragraph about many topics. "
|
||||
+ "deployment pipelines. yet another sentence entirely. a helpful guide to nothing.</p>");
|
||||
List<SearchHit> hits = search("cloud deployment guide", 20);
|
||||
assertEquals(2, hits.size(), "both pages contain all terms");
|
||||
assertEquals("Manual", hits.get(0).title(), "the exact-phrase page ranks first (phrase tier)");
|
||||
assertTrue(hits.get(0).score() > hits.get(1).score(), "exact-phrase score strictly higher");
|
||||
}
|
||||
|
||||
@Test
|
||||
void titlePhraseHitOutranksBodyPhraseHit() {
|
||||
CatalogEntry bodyHit = item("body", "Some Article", "");
|
||||
corpus(bodyHit, item("title", "Runway Deployment Guide", ""));
|
||||
body(bodyHit, "<p>Here is the runway deployment guide in the body text.</p>");
|
||||
List<SearchHit> hits = search("runway deployment guide", 20);
|
||||
assertEquals("Runway Deployment Guide", hits.get(0).title(),
|
||||
"the title-phrase page wins (tierPhraseTitle > tierPhraseBody)");
|
||||
}
|
||||
|
||||
@Test
|
||||
void theTierScoresAddUpAsDocumented() {
|
||||
// One title-phrase hit for a three-term query: any-terms (BM25, small) + exact title phrase (4000) +
|
||||
// all terms anywhere (300). The body has no phrase, so neither body tier fires.
|
||||
corpus(item("p", "Runway Deployment Guide", ""));
|
||||
double score = search("runway deployment guide", 20).get(0).score();
|
||||
assertTrue(score > 4300 && score < 4300 + 100, "4000 + 300 + a BM25 base, was " + score);
|
||||
}
|
||||
|
||||
// --------------------------------------------------------------------------------------------------- fuzzy
|
||||
|
||||
@Test
|
||||
void fuzzyQueryToleratesATypo() {
|
||||
CatalogEntry p = item("p", "Lucene Handbook", "");
|
||||
corpus(p);
|
||||
body(p, "<p>All about lucene.</p>");
|
||||
// "lucane" is 1 edit from "lucene" (and stays within the fuzzy budget after analysis).
|
||||
assertFalse(search("lucane", 20).isEmpty(), "a 1-edit typo still matches with fuzzy on");
|
||||
}
|
||||
|
||||
@Test
|
||||
void fuzzyCanBeTurnedOffPerSiteAndTheSaveAppliesToTheNextQuery() {
|
||||
CatalogEntry p = item("p", "Lucene Handbook", "");
|
||||
corpus(p);
|
||||
body(p, "<p>All about lucene.</p>");
|
||||
assertFalse(search("lucane", 20).isEmpty());
|
||||
luceneSettings.site(SITE, Map.of("fuzzy", false));
|
||||
assertTrue(search("lucane", 20).isEmpty(), "with fuzzy off, the typo no longer matches — no rebuild needed");
|
||||
assertFalse(search("lucene", 20).isEmpty(), "the exact term still matches with fuzzy off");
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------------------------ per-locale analyzers
|
||||
|
||||
@Test
|
||||
void englishAnalyzerStemsSoAQueryMatchesAStemmedForm() {
|
||||
CatalogEntry p = item("p", "Athletics", "");
|
||||
corpus(p);
|
||||
body(p, "<p>They run every morning.</p>");
|
||||
assertFalse(search("running", 20).isEmpty(), "English stemming: 'running' matches 'run'");
|
||||
}
|
||||
|
||||
@Test
|
||||
void spanishAnalyzerIsSelectedForASpanishSiteAndStems() {
|
||||
// A Spanish-default site: the SpanishAnalyzer stems "productos" and "producto" to the same root.
|
||||
site("tienda", Locale.forLanguageTag("es"));
|
||||
CatalogEntry cat = item("pages", "cat", "es", "Catálogo", "");
|
||||
corpus("tienda", cat);
|
||||
catalog.text("tienda", cat.compositeId(), "<p>Todos nuestros productos en oferta.</p>");
|
||||
List<SearchHit> hits = engine.search(new SearchQuery("tienda", "producto", Locale.forLanguageTag("es"), 20));
|
||||
assertFalse(hits.isEmpty(), "Spanish stemming: singular 'producto' matches plural 'productos'");
|
||||
}
|
||||
|
||||
@Test
|
||||
void unknownLocaleFallsBackToStandardAnalyzerAndStillMatches() {
|
||||
site("kl", Locale.forLanguageTag("tlh"));
|
||||
corpus("kl", item("pages", "p", "tlh", "Qapla", "victory"));
|
||||
assertFalse(engine.search(new SearchQuery("kl", "victory", Locale.forLanguageTag("tlh"), 20)).isEmpty(),
|
||||
"unknown locale still searches via the StandardAnalyzer fallback");
|
||||
assertFalse(LocaleAnalyzers.hasLanguageAnalyzer("tlh"), "no language analyzer for Klingon");
|
||||
assertTrue(LocaleAnalyzers.hasLanguageAnalyzer("es"), "Spanish has a language analyzer");
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------------------------------ heap vs disk
|
||||
|
||||
@Test
|
||||
void diskStorageIndexesAndSearchesLikeHeap(@TempDir Path tmp) {
|
||||
corpus(item("guide", "Runway Guide", "How to deploy."), item("other", "Runway Other", "Runway runway."));
|
||||
List<SearchHit> heap = search("runway guide", 20);
|
||||
storage.setStorage("disk");
|
||||
storage.setIndexRoot(tmp.toString());
|
||||
newEngine();
|
||||
List<SearchHit> disk = search("runway guide", 20);
|
||||
assertEquals("disk", engine.storageMode());
|
||||
assertEquals(heap, disk, "disk (MMapDirectory) answers exactly what heap answers, scores included");
|
||||
assertTrue(Files.isDirectory(tmp.resolve(SITE)), "a per-site index folder was created on disk");
|
||||
}
|
||||
|
||||
@Test
|
||||
void heapIsTheDefaultStorageMode() {
|
||||
assertEquals("heap", engine.storageMode());
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------------------------------ highlighting
|
||||
|
||||
@Test
|
||||
void highlightingWrapsTheHitInMarkTags() {
|
||||
CatalogEntry p = item("p", "Guide", "");
|
||||
corpus(p);
|
||||
body(p, "<p>Configuring the deployment pipeline is the first step of any release.</p>");
|
||||
List<SearchHit> hits = search("deployment", 20);
|
||||
assertEquals(1, hits.size());
|
||||
String snippet = hits.get(0).snippet();
|
||||
assertTrue(snippet.contains("<mark>deployment</mark>"),
|
||||
"the matched term is wrapped in <mark> in the query-focused snippet, was: " + snippet);
|
||||
}
|
||||
|
||||
@Test
|
||||
void highlightSnippetEscapesPageMarkupSoOnlyMarkTagsSurvive() {
|
||||
CatalogEntry p = item("p", "Guide", "");
|
||||
corpus(p);
|
||||
body(p, "<p>Use the <deployment> token and the deployment button to ship.</p>");
|
||||
String snippet = search("deployment", 20).get(0).snippet();
|
||||
assertTrue(snippet.contains("<mark>"), "a mark tag is present");
|
||||
assertFalse(snippet.contains("<deployment>"), "raw page angle brackets are escaped, not rendered as a tag");
|
||||
}
|
||||
|
||||
@Test
|
||||
void withoutABodyHitTheSnippetIsTheDescription() {
|
||||
corpus(item("p", "Runway", "A short summary."), item("q", "Lone Title", ""));
|
||||
assertEquals("A short summary.", search("runway", 20).get(0).snippet());
|
||||
assertEquals("", search("lone", 20).get(0).snippet(), "no body and no description: an empty snippet");
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------------------------- tuning knobs
|
||||
|
||||
@Test
|
||||
void titleBoostKnobRaisesATitleMatchOverABodyMatch() {
|
||||
CatalogEntry bodyHit = item("bodyhit", "Other", "");
|
||||
corpus(item("titlehit", "alpha", ""), bodyHit);
|
||||
body(bodyHit, "<p>alpha appears only in the body here.</p>");
|
||||
// Single-term query so the phrase tiers don't fire — the any-terms tier (where titleBoost applies) decides.
|
||||
luceneSettings.site(SITE, Map.of("titleBoost", 50.0));
|
||||
List<SearchHit> hits = search("alpha", 20);
|
||||
assertEquals(2, hits.size());
|
||||
assertEquals("alpha", hits.get(0).title(), "with a high titleBoost the title-match page ranks first");
|
||||
}
|
||||
|
||||
@Test
|
||||
void tierScoreKnobsChangeTheAbsoluteScore() {
|
||||
corpus(item("p", "Runway Deployment Guide", ""));
|
||||
double defaultScore = search("runway deployment guide", 20).get(0).score();
|
||||
luceneSettings.site(SITE, Map.of("tierPhraseTitle", 40000.0));
|
||||
double boostedScore = search("runway deployment guide", 20).get(0).score();
|
||||
assertTrue(boostedScore > defaultScore,
|
||||
"raising tierPhraseTitle raises the exact-title-phrase score: " + boostedScore + " > " + defaultScore);
|
||||
}
|
||||
|
||||
@Test
|
||||
void theDeclaredDefaultsRankExactlyLikeNoSettingsAtAll() {
|
||||
// PluginSettings hands the engine the descriptor's defaults under the stored values; they equal the code
|
||||
// fallbacks, so a site that never saved the form ranks as the engine's own defaults do.
|
||||
CatalogEntry p = item("p", "Runway Deployment Guide", "deploy");
|
||||
corpus(p, item("q", "Notes", "runway"));
|
||||
body(p, "<p>runway deployment guide and more</p>");
|
||||
List<SearchHit> bare = search("runway deployment guide", 20);
|
||||
luceneSettings.defaults(Map.of("fuzzy", true, "fuzzyBoost", 0.4, "titleBoost", 8.0, "descriptionBoost", 4.0,
|
||||
"tierPhraseTitle", 4000, "tierPhraseBody", 2000, "tierNearPhrase", 800, "tierAllTerms", 300));
|
||||
assertEquals(bare, search("runway deployment guide", 20));
|
||||
}
|
||||
|
||||
@Test
|
||||
void malformedKnobValuesFallBackToDefaultsAndStillSearch() {
|
||||
corpus(item("p", "Runway Guide", ""));
|
||||
luceneSettings.site(SITE, Map.of(
|
||||
"titleBoost", "not-a-number", "fuzzyBoost", "", "tierPhraseTitle", "abc", "fuzzy", "maybe"));
|
||||
assertFalse(search("runway", 20).isEmpty(), "malformed config degrades to defaults, never breaks search");
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------- console
|
||||
|
||||
@Test
|
||||
void consoleModelReportsIndexSizeTitleBoostAndStorageMode() {
|
||||
corpus(item("a", "A", ""), item("b", "B", ""));
|
||||
LuceneAdminModel model = new LuceneAdminModel(engine);
|
||||
assertEquals(2, model.indexedPages(SITE), "the corpus is what the console reports");
|
||||
assertEquals("heap", model.storageMode());
|
||||
assertEquals("search/lucene", model.engineKey());
|
||||
assertEquals("8.0", model.titleBoost(SITE));
|
||||
luceneSettings.site(SITE, Map.of("titleBoost", 9.5));
|
||||
assertEquals("9.5", model.titleBoost(SITE), "the effective, per-site value");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
package mx.quest.searchlucene;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/** The app-level storage settings: default heap, tolerant enum binding, and a never-blank index root. */
|
||||
class LuceneStoragePropsTest {
|
||||
|
||||
@Test
|
||||
void defaultsToHeapWithADefaultIndexRoot() {
|
||||
LuceneStorageProps p = new LuceneStorageProps();
|
||||
assertEquals(LuceneStorageProps.Storage.HEAP, p.getStorage());
|
||||
assertFalse(p.isDisk());
|
||||
assertFalse(p.getIndexRoot().isBlank());
|
||||
}
|
||||
|
||||
@Test
|
||||
void storageBindingIsCaseInsensitiveAndTolerant() {
|
||||
LuceneStorageProps p = new LuceneStorageProps();
|
||||
p.setStorage("disk");
|
||||
assertTrue(p.isDisk());
|
||||
p.setStorage("HEAP");
|
||||
assertFalse(p.isDisk());
|
||||
p.setStorage("DISK");
|
||||
assertTrue(p.isDisk());
|
||||
}
|
||||
|
||||
@Test
|
||||
void unknownOrBlankStorageFallsBackToHeap() {
|
||||
LuceneStorageProps p = new LuceneStorageProps();
|
||||
p.setStorage("disk");
|
||||
p.setStorage("nonsense"); // degrade-don't-crash: not a crash, resets to HEAP
|
||||
assertEquals(LuceneStorageProps.Storage.HEAP, p.getStorage());
|
||||
p.setStorage("disk");
|
||||
p.setStorage("");
|
||||
assertEquals(LuceneStorageProps.Storage.HEAP, p.getStorage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void blankIndexRootRestoresTheDefault() {
|
||||
LuceneStorageProps p = new LuceneStorageProps();
|
||||
p.setIndexRoot("/data/idx");
|
||||
assertEquals("/data/idx", p.getIndexRoot());
|
||||
p.setIndexRoot(" ");
|
||||
assertFalse(p.getIndexRoot().isBlank(), "blank restores the default, never leaves an empty path");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
package mx.quest.searchlucene;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/** Defensive resolution of the per-tenant ranking knobs: defaults, coercion, clamping, and garbage tolerance. */
|
||||
class RankingConfigTest {
|
||||
|
||||
@Test
|
||||
void emptyConfigYieldsTheHistoricalDefaults() {
|
||||
RankingConfig c = RankingConfig.defaults();
|
||||
assertTrue(c.fuzzy());
|
||||
assertEquals(RankingConfig.DEF_FUZZY_BOOST, c.fuzzyBoost());
|
||||
assertEquals(RankingConfig.DEF_TITLE_BOOST, c.titleBoost());
|
||||
assertEquals(RankingConfig.DEF_DESCRIPTION_BOOST, c.descriptionBoost());
|
||||
assertEquals(RankingConfig.DEF_TIER_PHRASE_TITLE, c.tierPhraseTitle());
|
||||
assertEquals(RankingConfig.DEF_TIER_PHRASE_BODY, c.tierPhraseBody());
|
||||
assertEquals(RankingConfig.DEF_TIER_NEAR_PHRASE, c.tierNearPhrase());
|
||||
assertEquals(RankingConfig.DEF_TIER_ALL_TERMS, c.tierAllTerms());
|
||||
}
|
||||
|
||||
@Test
|
||||
void numericAndStringValuesAreBothCoerced() {
|
||||
RankingConfig c = RankingConfig.from(Map.of("titleBoost", 12.5, "descriptionBoost", "3.25"));
|
||||
assertEquals(12.5f, c.titleBoost());
|
||||
assertEquals(3.25f, c.descriptionBoost());
|
||||
}
|
||||
|
||||
@Test
|
||||
void booleanFlagAcceptsBooleanAndTruthyStrings() {
|
||||
assertTrue(RankingConfig.from(Map.of("fuzzy", true)).fuzzy());
|
||||
assertFalse(RankingConfig.from(Map.of("fuzzy", false)).fuzzy());
|
||||
assertTrue(RankingConfig.from(Map.of("fuzzy", "on")).fuzzy());
|
||||
assertTrue(RankingConfig.from(Map.of("fuzzy", "1")).fuzzy());
|
||||
assertFalse(RankingConfig.from(Map.of("fuzzy", "off")).fuzzy());
|
||||
}
|
||||
|
||||
@Test
|
||||
void garbageAndBlanksFallBackToDefaults() {
|
||||
Map<String, Object> cfg = new HashMap<>();
|
||||
cfg.put("titleBoost", "not-a-number");
|
||||
cfg.put("fuzzyBoost", "");
|
||||
cfg.put("tierPhraseBody", "NaN");
|
||||
RankingConfig c = RankingConfig.from(cfg);
|
||||
assertEquals(RankingConfig.DEF_TITLE_BOOST, c.titleBoost());
|
||||
assertEquals(RankingConfig.DEF_FUZZY_BOOST, c.fuzzyBoost());
|
||||
assertEquals(RankingConfig.DEF_TIER_PHRASE_BODY, c.tierPhraseBody());
|
||||
}
|
||||
|
||||
@Test
|
||||
void negativeValuesAreClampedToZeroAndHugeValuesAreCapped() {
|
||||
RankingConfig c = RankingConfig.from(Map.of("titleBoost", -5.0, "tierAllTerms", 9.9e12));
|
||||
assertEquals(0f, c.titleBoost(), "negative boost clamped to 0");
|
||||
assertTrue(c.tierAllTerms() <= 1_000_001f, "a huge value is capped, not left to overflow the score math");
|
||||
}
|
||||
}
|
||||
+291
@@ -0,0 +1,291 @@
|
||||
package mx.quest.searchlucene;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertInstanceOf;
|
||||
import static org.junit.jupiter.api.Assertions.assertSame;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.Reader;
|
||||
import java.lang.reflect.Method;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Properties;
|
||||
import java.util.Set;
|
||||
import java.util.TreeSet;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
import mx.quest.runway.spi.model.SiteView;
|
||||
import mx.quest.runway.spi.service.PluginSettings;
|
||||
import mx.quest.runway.spi.service.SiteEventListener;
|
||||
import mx.quest.runway.spi.service.Sites;
|
||||
import mx.quest.runway.spi.testkit.FakeContentCatalog;
|
||||
import mx.quest.runway.spi.testkit.FakePluginSettings;
|
||||
import mx.quest.runway.spi.testkit.FakeSiteServices;
|
||||
import mx.quest.search.SiteSearchCorpus;
|
||||
import mx.quest.search.spi.SearchCorpus;
|
||||
import mx.quest.search.spi.SiteSearchEngine;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.boot.context.properties.EnableConfigurationProperties;
|
||||
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.core.env.MapPropertySource;
|
||||
import org.yaml.snakeyaml.Yaml;
|
||||
|
||||
/**
|
||||
* The plugin's contract with the host and with the search plugin, checked at build time: the wiring over published
|
||||
* services only (SPI services from the kernel, {@link SearchCorpus} from search) including the app-level storage
|
||||
* settings bound under {@code runway.plugin.search-lucene}; the bean-name rule; the bean names the templates reference;
|
||||
* the descriptor (SPI floor, release version, the {@code requires:} gates); the code fallbacks equal to the descriptor
|
||||
* defaults; the i18n bundles; and that the compiled classes link nothing of the host but the SPI and nothing of the
|
||||
* search plugin but its SPI package — the same things the kernel's load-time checks warn about (and refuse from
|
||||
* Runway 1.0).
|
||||
*/
|
||||
class SearchLuceneConfigTest {
|
||||
|
||||
private static final String PREFIX = "searchLucene";
|
||||
|
||||
/** Stands in for the host's Spring Boot auto-configuration: the binder behind {@code @ConfigurationProperties}. */
|
||||
@Configuration(proxyBeanMethods = false)
|
||||
@EnableConfigurationProperties
|
||||
static class HostBinding {
|
||||
}
|
||||
|
||||
private static Set<String> beanMethodNames() {
|
||||
return Arrays.stream(SearchLuceneConfig.class.getDeclaredMethods())
|
||||
.filter(m -> m.isAnnotationPresent(Bean.class))
|
||||
.map(Method::getName)
|
||||
.collect(Collectors.toCollection(TreeSet::new));
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private static Map<String, Object> descriptor() throws IOException {
|
||||
try (Reader in = Files.newBufferedReader(Path.of("plugin.yml"), StandardCharsets.UTF_8)) {
|
||||
return (Map<String, Object>) new Yaml().load(in);
|
||||
}
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private static Map<String, Object> declaredDefaults(String section) throws IOException {
|
||||
Map<String, Object> out = new LinkedHashMap<>();
|
||||
for (Map<String, Object> s : (List<Map<String, Object>>) descriptor().get(section)) {
|
||||
if (s.containsKey("default")) {
|
||||
out.put((String) s.get("key"), s.get("default"));
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
@Test
|
||||
void wiresEverythingFromPublishedServicesUnderPrefixedNames(@org.junit.jupiter.api.io.TempDir Path index)
|
||||
throws IOException {
|
||||
FakeSiteServices kernel = new FakeSiteServices()
|
||||
.site(new SiteView("acme", "Acme", Locale.ENGLISH, List.of(Locale.ENGLISH), null));
|
||||
FakeContentCatalog catalog = new FakeContentCatalog()
|
||||
.entry("acme", LuceneSearchEngineTest.item("home", "Runway home", ""))
|
||||
.entry("acme", LuceneSearchEngineTest.item("privacy", "Runway privacy", ""));
|
||||
SearchCorpus corpus = new SiteSearchCorpus(catalog,
|
||||
new FakePluginSettings().site("acme", Map.of("exclude", List.of("privacy"))));
|
||||
try (AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext()) {
|
||||
ctx.getEnvironment().getPropertySources().addFirst(new MapPropertySource("plugin-settings", Map.of(
|
||||
"runway.plugin.search-lucene.storage", "disk",
|
||||
"runway.plugin.search-lucene.indexRoot", index.toString())));
|
||||
ctx.registerBean(PluginSettings.class, () -> new FakePluginSettings()
|
||||
.site("acme", Map.of("titleBoost", 9.5)));
|
||||
ctx.registerBean(Sites.class, () -> kernel);
|
||||
ctx.registerBean(SearchCorpus.class, () -> corpus);
|
||||
ctx.register(HostBinding.class, SearchLuceneConfig.class);
|
||||
ctx.refresh();
|
||||
|
||||
LuceneStorageProps props = ctx.getBean("searchLuceneStorageProps", LuceneStorageProps.class);
|
||||
assertTrue(props.isDisk(), "the app-level settings bind under runway.plugin.search-lucene");
|
||||
assertEquals(index.toString(), props.getIndexRoot());
|
||||
|
||||
LuceneSearchEngine engine = ctx.getBean("searchLuceneEngine", LuceneSearchEngine.class);
|
||||
assertEquals(List.of(engine), List.copyOf(ctx.getBeansOfType(SiteSearchEngine.class).values()),
|
||||
"one engine, collected by the search plugin's List<SiteSearchEngine>");
|
||||
assertEquals(1, engine.indexedDocuments("acme"), "the engine indexes the corpus (privacy is excluded)");
|
||||
assertEquals("disk", engine.storageMode());
|
||||
assertTrue(Files.isDirectory(index.resolve("acme")));
|
||||
|
||||
Map<String, SiteEventListener> listeners = ctx.getBeansOfType(SiteEventListener.class);
|
||||
assertEquals(Set.of("searchLuceneSiteEvents"), listeners.keySet(), "one listener, collected by type");
|
||||
assertEquals(SiteEventListener.Phase.CONSUMER, listeners.get("searchLuceneSiteEvents").phase());
|
||||
|
||||
LuceneAdminModel model = ctx.getBean("searchLuceneAdminModel", LuceneAdminModel.class);
|
||||
assertEquals("9.5", model.titleBoost("acme"), "the knobs come from the injected PluginSettings");
|
||||
assertSame(engine, readEngine(model));
|
||||
|
||||
for (String name : ctx.getBeanDefinitionNames()) {
|
||||
Class<?> type = ctx.getType(name);
|
||||
if (type != null && type.getPackageName().equals("mx.quest.searchlucene")
|
||||
&& !name.equals(SearchLuceneConfig.class.getName())
|
||||
&& !name.equals("searchLuceneConfig")) {
|
||||
assertTrue(name.startsWith(PREFIX), "every plugin bean name starts with 'searchLucene': " + name);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static Object readEngine(LuceneAdminModel model) {
|
||||
try {
|
||||
var field = LuceneAdminModel.class.getDeclaredField("engine");
|
||||
field.setAccessible(true);
|
||||
return field.get(model);
|
||||
} catch (ReflectiveOperationException e) {
|
||||
throw new AssertionError(e);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void everyBeanNameStartsWithThePluginIdInLowerCamelCase() {
|
||||
assertEquals(Set.of("searchLuceneStorageProps", "searchLuceneEngine", "searchLuceneSiteEvents",
|
||||
"searchLuceneAdminModel"), beanMethodNames());
|
||||
for (Method m : SearchLuceneConfig.class.getDeclaredMethods()) {
|
||||
Bean bean = m.getAnnotation(Bean.class);
|
||||
if (bean != null) {
|
||||
for (String alias : bean.name()) {
|
||||
assertTrue(alias.startsWith(PREFIX), "an explicit bean name must start with " + PREFIX + ": " + alias);
|
||||
}
|
||||
}
|
||||
}
|
||||
assertFalse(SearchLuceneConfig.class.isAnnotationPresent(EnableConfigurationProperties.class),
|
||||
"@EnableConfigurationProperties names its bean '<prefix>-<class>', which breaks the bean-name rule");
|
||||
}
|
||||
|
||||
@Test
|
||||
void everyBeanTheTemplatesReferenceIsOneOfOurs() throws IOException {
|
||||
Set<String> referenced = new TreeSet<>();
|
||||
try (Stream<Path> files = Files.list(Path.of("templates"))) {
|
||||
for (Path file : files.filter(p -> p.toString().endsWith(".th.xml")).toList()) {
|
||||
String live = Files.readString(file, StandardCharsets.UTF_8).replaceAll("(?s)<!--.*?-->", "");
|
||||
Matcher m = Pattern.compile("@(\\w+)\\.").matcher(live);
|
||||
while (m.find()) {
|
||||
referenced.add(m.group(1));
|
||||
}
|
||||
}
|
||||
}
|
||||
assertEquals(Set.of("searchLuceneAdminModel"), referenced, "the console templates read the admin model only");
|
||||
assertTrue(beanMethodNames().containsAll(referenced), "templates reference unknown beans: " + referenced);
|
||||
}
|
||||
|
||||
@Test
|
||||
void theDescriptorDeclaresTheFloorsAndTheReleaseVersion() throws IOException {
|
||||
Map<String, Object> yml = descriptor();
|
||||
assertEquals(">=1.0.0", yml.get("requiresSpi"), "built for the frozen SPI 1.0.0 contract");
|
||||
assertEquals(List.of("search >= 2.2.0", "lucene-provider == 10.4.0"), yml.get("requires"),
|
||||
"search 2.2.0 submits a localized box to the localized results page, which reaches a language's index"
|
||||
+ " (2.1.0 was the first with the matched-words SearchHit); Lucene is pinned to the binaries");
|
||||
assertEquals("mx.quest.searchlucene.SearchLuceneConfig", yml.get("mainClass"));
|
||||
String pom = Files.readString(Path.of("pom.xml"), StandardCharsets.UTF_8);
|
||||
Matcher version = Pattern.compile("<artifactId>runway-plugin-search-lucene</artifactId>\\s*<version>([^<]+)")
|
||||
.matcher(pom);
|
||||
assertTrue(version.find());
|
||||
assertEquals(version.group(1), String.valueOf(yml.get("version")), "plugin.yml and pom.xml agree on the version");
|
||||
assertEquals("3.3.0", version.group(1));
|
||||
assertFalse(pom.contains("<artifactId>runway-app</artifactId>"), "no runway-app dependency in any scope");
|
||||
assertTrue(pom.contains("<project.build.outputTimestamp>2026-10-21T17:23:00Z</project.build.outputTimestamp>"));
|
||||
assertTrue(pom.contains("<lucene.version>10.4.0</lucene.version>"),
|
||||
"the compiled-against Lucene equals the lucene-provider pin");
|
||||
assertFalse(yml.containsKey("siteData"), "the plugin keeps no per-site data (the index is derived)");
|
||||
}
|
||||
|
||||
@Test
|
||||
void theCodeFallbacksEqualTheDescriptorDefaults() throws IOException {
|
||||
Map<String, Object> site = declaredDefaults("siteSettings");
|
||||
RankingConfig code = RankingConfig.defaults();
|
||||
assertEquals(site.get("fuzzy"), code.fuzzy());
|
||||
assertEquals(((Number) site.get("fuzzyBoost")).floatValue(), code.fuzzyBoost());
|
||||
assertEquals(((Number) site.get("titleBoost")).floatValue(), code.titleBoost());
|
||||
assertEquals(((Number) site.get("descriptionBoost")).floatValue(), code.descriptionBoost());
|
||||
assertEquals(((Number) site.get("tierPhraseTitle")).floatValue(), code.tierPhraseTitle());
|
||||
assertEquals(((Number) site.get("tierPhraseBody")).floatValue(), code.tierPhraseBody());
|
||||
assertEquals(((Number) site.get("tierNearPhrase")).floatValue(), code.tierNearPhrase());
|
||||
assertEquals(((Number) site.get("tierAllTerms")).floatValue(), code.tierAllTerms());
|
||||
assertEquals(8, site.size(), "every declared default is checked above");
|
||||
assertEquals(code, RankingConfig.from(site), "the declared defaults resolve to the code defaults");
|
||||
|
||||
Map<String, Object> app = declaredDefaults("settings");
|
||||
LuceneStorageProps props = new LuceneStorageProps();
|
||||
assertEquals(app.get("storage"), props.getStorage().name().toLowerCase(Locale.ROOT));
|
||||
assertEquals(app.get("indexRoot"), props.getIndexRoot());
|
||||
}
|
||||
|
||||
@Test
|
||||
void theEnglishAndSpanishBundlesDefineTheSameKeys() throws IOException {
|
||||
Set<String> en = keys("i18n/messages.properties");
|
||||
assertEquals(en, keys("i18n/messages_es.properties"));
|
||||
Set<String> labels = new TreeSet<>();
|
||||
for (String section : List.of("settings", "siteSettings", "permissions")) {
|
||||
@SuppressWarnings("unchecked")
|
||||
List<Map<String, Object>> entries = (List<Map<String, Object>>) descriptor().get(section);
|
||||
entries.forEach(e -> labels.add((String) e.get("label")));
|
||||
}
|
||||
assertTrue(en.containsAll(labels), "every descriptor label has words: " + labels);
|
||||
}
|
||||
|
||||
private static Set<String> keys(String file) throws IOException {
|
||||
Properties p = new Properties();
|
||||
try (Reader in = Files.newBufferedReader(Path.of(file), StandardCharsets.UTF_8)) {
|
||||
p.load(in);
|
||||
}
|
||||
return new TreeSet<>(p.stringPropertyNames());
|
||||
}
|
||||
|
||||
/** Every class file this plugin ships, with its constant pool as text (Latin-1 keeps one char per byte). */
|
||||
private static Map<String, String> compiledClasses() throws IOException {
|
||||
Path classes = Path.of("target", "classes");
|
||||
Map<String, String> out = new LinkedHashMap<>();
|
||||
try (Stream<Path> files = Files.walk(classes)) {
|
||||
for (Path file : files.filter(p -> p.toString().endsWith(".class")).sorted().toList()) {
|
||||
out.put(classes.relativize(file).toString().replace('\\', '/'),
|
||||
new String(Files.readAllBytes(file), StandardCharsets.ISO_8859_1));
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
@Test
|
||||
void theCompiledClassesLinkNoHostInternalsAndOnlyTheSearchSpi() throws IOException {
|
||||
Pattern host = Pattern.compile("mx[/.]quest[/.]runway[/.](?!spi[/.])[\\w/.$]*");
|
||||
// search's own classes (SiteSearchCorpus, SearchSiteConfig, …) are its internals: only its SPI package is a
|
||||
// contract, and only the SPI package is guaranteed to keep its shape across search releases.
|
||||
Pattern searchInternals = Pattern.compile("mx[/.]quest[/.]search[/.](?!spi[/.])[\\w/.$]*");
|
||||
List<String> problems = new ArrayList<>();
|
||||
Map<String, String> classes = compiledClasses();
|
||||
classes.forEach((rel, pool) -> {
|
||||
if (!rel.startsWith("mx/quest/searchlucene/")) {
|
||||
problems.add(rel + " lives outside mx.quest.searchlucene");
|
||||
}
|
||||
for (Pattern p : List.of(host, searchInternals)) {
|
||||
Matcher m = p.matcher(pool);
|
||||
while (m.find()) {
|
||||
problems.add(rel + " → " + m.group());
|
||||
}
|
||||
}
|
||||
});
|
||||
assertTrue(classes.size() >= 8, "the compiled classes were found (" + classes.size() + ")");
|
||||
assertTrue(problems.isEmpty(), "linkage outside the published contracts: " + problems);
|
||||
assertTrue(classes.values().stream().anyMatch(pool -> pool.contains("mx/quest/search/spi/SearchCorpus")),
|
||||
"the engine reads the search plugin's SearchCorpus");
|
||||
}
|
||||
|
||||
@Test
|
||||
void theCompiledClassesLinkNoCaffeine() throws IOException {
|
||||
// Caffeine is a kernel implementation detail, not one of the platform libraries the kernel promises
|
||||
// (Spring, Spring Boot, Spring Security, Thymeleaf, Jackson, Jakarta EE): a plugin must not link it.
|
||||
compiledClasses().forEach((rel, pool) ->
|
||||
assertFalse(pool.contains("com/github/benmanes"), rel + " links Caffeine"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
<!-- Admin status fragment — the filename `admin` makes the host render it below this plugin's per-tenant
|
||||
settings form (the titleBoost tuning). Bare fragment; binding in admin.th.xml. -->
|
||||
<div class="card mt-3">
|
||||
<div class="card-header"><h3 class="card-title" id="la-title">Lucene index status</h3></div>
|
||||
<div class="card-body">
|
||||
<div class="datagrid">
|
||||
<div class="datagrid-item">
|
||||
<div class="datagrid-title" id="la-l-engine">Engine</div>
|
||||
<div class="datagrid-content" id="la-engine">search/lucene</div>
|
||||
</div>
|
||||
<div class="datagrid-item">
|
||||
<div class="datagrid-title" id="la-l-pages">Indexed pages</div>
|
||||
<div class="datagrid-content" id="la-pages">0</div>
|
||||
</div>
|
||||
<div class="datagrid-item">
|
||||
<div class="datagrid-title" id="la-l-storage">Storage</div>
|
||||
<div class="datagrid-content" id="la-storage">heap</div>
|
||||
</div>
|
||||
<div class="datagrid-item">
|
||||
<div class="datagrid-title" id="la-l-boost">Title boost</div>
|
||||
<div class="datagrid-content" id="la-boost">8.0</div>
|
||||
</div>
|
||||
</div>
|
||||
<p class="text-secondary small mt-2 mb-0" id="la-note">
|
||||
This engine supersedes the built-in search whenever it is installed. The index refreshes
|
||||
automatically as pages change; no manual rebuild is needed.</p>
|
||||
</div>
|
||||
</div>
|
||||
@@ -0,0 +1,14 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!-- Admin fragment logic. Values from ${@searchLuceneAdminModel...(tenantSiteId)}. -->
|
||||
<thlogic>
|
||||
<attr sel="#la-title" th:text="#{searchlucene.admin.title}"/>
|
||||
<attr sel="#la-l-engine" th:text="#{searchlucene.admin.engine}"/>
|
||||
<attr sel="#la-engine" th:text="${@searchLuceneAdminModel.engineKey()}"/>
|
||||
<attr sel="#la-l-pages" th:text="#{searchlucene.admin.pages}"/>
|
||||
<attr sel="#la-pages" th:text="${@searchLuceneAdminModel.indexedPages(tenantSiteId)}"/>
|
||||
<attr sel="#la-l-storage" th:text="#{searchlucene.admin.storage}"/>
|
||||
<attr sel="#la-storage" th:text="${@searchLuceneAdminModel.storageMode()}"/>
|
||||
<attr sel="#la-l-boost" th:text="#{searchlucene.admin.boost}"/>
|
||||
<attr sel="#la-boost" th:text="${@searchLuceneAdminModel.titleBoost(tenantSiteId)}"/>
|
||||
<attr sel="#la-note" th:text="#{searchlucene.admin.note}"/>
|
||||
</thlogic>
|
||||
@@ -0,0 +1,16 @@
|
||||
<!-- Tenant dashboard card fragment — __plugin__/search-lucene/dashboard. Bare fragment; binding in .th.xml. -->
|
||||
<div class="card">
|
||||
<div class="card-status-start bg-purple"></div>
|
||||
<div class="card-body">
|
||||
<div class="d-flex align-items-center">
|
||||
<span class="bg-purple-lt avatar"><i class="fa-solid fa-layer-group"></i></span>
|
||||
<div class="ms-3">
|
||||
<div class="fw-bold" id="lc-title">Lucene search index</div>
|
||||
<div class="text-secondary small">
|
||||
<span id="lc-pages">0</span> <span id="lc-pages-lbl">indexed pages</span>
|
||||
· <span id="lc-engine">search/lucene</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -0,0 +1,8 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!-- Dashboard card logic. Values from ${@searchLuceneAdminModel...(tenantSiteId)}. -->
|
||||
<thlogic>
|
||||
<attr sel="#lc-title" th:text="#{searchlucene.card.title}"/>
|
||||
<attr sel="#lc-pages" th:text="${@searchLuceneAdminModel.indexedPages(tenantSiteId)}"/>
|
||||
<attr sel="#lc-pages-lbl" th:text="#{searchlucene.card.pages}"/>
|
||||
<attr sel="#lc-engine" th:text="${@searchLuceneAdminModel.engineKey()}"/>
|
||||
</thlogic>
|
||||
Reference in new issue
Block a user