Merge branch 'master' of gitea.51mars.com:Oak-Team/oak-domain

This commit is contained in:
Xu Chang 2024-03-29 18:31:36 +08:00
commit fa24031c44
50 changed files with 1330 additions and 948 deletions

232
LICENSE Normal file
View File

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

3
README.md Normal file
View File

@ -0,0 +1,3 @@
# oak-domain
oak-domain

View File

@ -13,7 +13,7 @@ export type OpSchema = EntityShape & {
extra?: Object | null;
operatorId?: ForeignKey<"user"> | null;
targetEntity: String<32>;
bornAt: Datetime;
bornAt?: Datetime | null;
};
export type OpAttr = keyof OpSchema;
export type Schema = EntityShape & {
@ -23,7 +23,7 @@ export type Schema = EntityShape & {
extra?: Object | null;
operatorId?: ForeignKey<"user"> | null;
targetEntity: String<32>;
bornAt: Datetime;
bornAt?: Datetime | null;
operator?: User.Schema | null;
operEntity$oper?: Array<OperEntity.Schema>;
operEntity$oper$$aggr?: AggregationResult<OperEntity.Schema>;

View File

@ -33,7 +33,6 @@ exports.desc = {
}
},
bornAt: {
notNull: true,
type: "datetime"
}
},

View File

@ -1,5 +0,0 @@
import { EntityDict } from '../base-app-domain';
import { AsyncContext } from '../store/AsyncRowStore';
import { SyncContext } from '../store/SyncRowStore';
import { StorageSchema, EntityDict as BaseEntityDict, Checker } from '../types';
export declare function createDynamicCheckers<ED extends EntityDict & BaseEntityDict, Cxt extends AsyncContext<ED> | SyncContext<ED>>(schema: StorageSchema<ED>): Checker<ED, keyof ED, Cxt>[];

View File

@ -1,13 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.createDynamicCheckers = void 0;
const checker_1 = require("../store/checker");
const modi_1 = require("../store/modi");
function createDynamicCheckers(schema) {
const checkers = [];
checkers.push(...(0, modi_1.createModiRelatedCheckers)(schema));
checkers.push(...(0, checker_1.createRemoveCheckers)(schema));
checkers.push(...(0, checker_1.createCreateCheckers)(schema));
return checkers;
}
exports.createDynamicCheckers = createDynamicCheckers;

View File

@ -8,5 +8,5 @@ export interface Schema extends EntityShape {
extra?: Object;
operator?: User;
targetEntity: String<32>;
bornAt: Datetime;
bornAt?: Datetime;
}

View File

@ -380,7 +380,7 @@ class CascadeStore extends RowStore_1.RowStore {
data: projection2[attr],
filter: {
id: {
$in: entityIds
$in: (0, lodash_1.difference)(entityIds, subRows.map(ele => ele.id)),
},
},
},
@ -463,7 +463,7 @@ class CascadeStore extends RowStore_1.RowStore {
data: projection2[attr],
filter: {
id: {
$in: ids
$in: (0, lodash_1.difference)(ids, subRows.map(ele => ele.id))
},
},
}
@ -1163,7 +1163,7 @@ class CascadeStore extends RowStore_1.RowStore {
data,
operatorId,
targetEntity: entity,
bornAt: bornAt || now,
bornAt,
operEntity$oper: data instanceof Array ? {
id: 'dummy',
action: 'create',
@ -1322,7 +1322,7 @@ class CascadeStore extends RowStore_1.RowStore {
action,
data,
targetEntity: entity,
bornAt: bornAt || now,
bornAt,
operatorId,
operEntity$oper: {
id: 'dummy',
@ -1333,6 +1333,9 @@ class CascadeStore extends RowStore_1.RowStore {
entity: entity,
})))
},
filter: {
id: { $in: ids },
}
},
};
const closeRootMode = context.openRootMode();
@ -1453,7 +1456,7 @@ class CascadeStore extends RowStore_1.RowStore {
}
}
cascadeUpdate(entity, operation, context, option) {
const { action, data, filter, id, bornAt } = operation;
const { action, data, filter } = operation;
let opData;
const wholeBeforeFns = [];
const wholeAfterFns = [];
@ -1493,7 +1496,7 @@ class CascadeStore extends RowStore_1.RowStore {
* @param option
*/
async cascadeUpdateAsync(entity, operation, context, option) {
const { action, data, filter, id, bornAt } = operation;
const { action, data, filter, bornAt } = operation;
let opData;
const wholeBeforeFns = [];
const wholeAfterFns = [];

5
lib/store/IntrinsicCheckers.d.ts vendored Normal file
View File

@ -0,0 +1,5 @@
import { ActionDictOfEntityDict, Checker, EntityDict, StorageSchema, AttrUpdateMatrix } from "../types";
import { SyncContext } from "./SyncRowStore";
import { AsyncContext } from "./AsyncRowStore";
import { EntityDict as BaseEntityDict } from '../base-app-domain/EntityDict';
export declare function makeIntrinsicCheckers<ED extends EntityDict & BaseEntityDict, Cxt extends AsyncContext<ED>, FrontCxt extends SyncContext<ED>>(schema: StorageSchema<ED>, actionDefDict: ActionDictOfEntityDict<ED>, attrUpdateMatrix?: AttrUpdateMatrix<ED>): Checker<ED, keyof ED, Cxt | FrontCxt>[];

View File

@ -1,53 +1,12 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.makeIntrinsicCTWs = exports.getFullProjection = void 0;
exports.makeIntrinsicCheckers = void 0;
const types_1 = require("../types");
const lodash_1 = require("../utils/lodash");
const filter_1 = require("./filter");
const checkers_1 = require("../checkers");
const triggers_1 = require("../triggers");
const actionAuth_1 = require("./actionAuth");
function getFullProjection(entity, schema) {
const { attributes } = schema[entity];
const projection = {
id: 1,
$$createAt$$: 1,
$$updateAt$$: 1,
$$deleteAt$$: 1,
};
Object.keys(attributes).forEach((k) => Object.assign(projection, {
[k]: 1,
}));
return projection;
}
exports.getFullProjection = getFullProjection;
function makeIntrinsicWatchers(schema) {
const watchers = [];
for (const entity in schema) {
const { attributes } = schema[entity];
const { expiresAt, expired } = attributes;
if (expiresAt && expiresAt.type === 'datetime' && expired && expired.type === 'boolean') {
// 如果有定义expiresAt和expired则自动生成一个检查的watcher
watchers.push({
entity,
name: `对象${entity}上的过期自动watcher`,
filter: () => {
return {
expired: false,
expiresAt: {
$lte: Date.now(),
},
};
},
action: 'update',
actionData: {
expired: true,
},
});
}
}
return watchers;
}
const modi_1 = require("./modi");
const checker_1 = require("./checker");
const action_1 = require("../actions/action");
function checkUniqueBetweenRows(rows, uniqAttrs) {
// 先检查这些行本身之间有无unique冲突
const dict = {};
@ -105,71 +64,8 @@ function checkUnique(entity, row, context, uniqAttrs, extraFilter) {
const count = context.count(entity, { filter: filter2 }, { dontCollect: true });
return checkCountLessThan(count, uniqAttrs, 0, row.id);
}
function makeIntrinsicCTWs(schema, actionDefDict) {
const checkers = (0, checkers_1.createDynamicCheckers)(schema);
const triggers = (0, triggers_1.createDynamicTriggers)(schema);
// action状态转换矩阵相应的checker
for (const entity in actionDefDict) {
for (const attr in actionDefDict[entity]) {
const def = actionDefDict[entity][attr];
const { stm, is } = def;
for (const action in stm) {
const actionStm = stm[action];
const conditionalFilter = typeof actionStm[0] === 'string' ? {
[attr]: actionStm[0],
} : {
[attr]: {
$in: actionStm[0],
},
};
checkers.push({
action: action,
type: 'row',
entity,
filter: conditionalFilter,
errMsg: '',
});
// 这里用data类型的checker改数据了不太好先这样
checkers.push({
action: action,
type: 'data',
entity,
checker: (data) => {
Object.assign(data, {
[attr]: stm[action][1],
});
}
});
}
if (is) {
checkers.push({
action: 'create',
type: 'data',
entity,
priority: 10,
checker: (data) => {
if (data instanceof Array) {
data.forEach(ele => {
if (!ele[attr]) {
Object.assign(ele, {
[attr]: is,
});
}
});
}
else {
if (!data[attr]) {
Object.assign(data, {
[attr]: is,
});
}
}
}
});
}
}
}
// unique索引相应的checker
function createUniqueCheckers(schema) {
const checkers = [];
for (const entity in schema) {
const { indexes } = schema[entity];
if (indexes) {
@ -181,7 +77,7 @@ function makeIntrinsicCTWs(schema, actionDefDict) {
entity,
action: 'create',
type: 'logicalData',
priority: types_1.CHECKER_MAX_PRIORITY,
priority: types_1.CHECKER_MAX_PRIORITY, // 优先级要放在最低所有前置的checker/trigger将数据完整之后再在这里检测
checker: (operation, context) => {
const { data } = operation;
if (data instanceof Array) {
@ -197,9 +93,9 @@ function makeIntrinsicCTWs(schema, actionDefDict) {
}
}, {
entity,
action: 'update',
action: 'update', // 只检查update其它状态转换的action应该不会涉及unique约束的属性
type: 'logicalData',
priority: types_1.CHECKER_MAX_PRIORITY,
priority: types_1.CHECKER_MAX_PRIORITY, // 优先级要放在最低所有前置的checker/trigger将数据完整之后再在这里检测
checker: (operation, context) => {
const { data, filter: operationFilter } = operation;
if (data) {
@ -268,11 +164,145 @@ function makeIntrinsicCTWs(schema, actionDefDict) {
}
}
}
triggers.push(...actionAuth_1.triggers);
return {
triggers,
checkers,
watchers: makeIntrinsicWatchers(schema),
};
return checkers;
}
exports.makeIntrinsicCTWs = makeIntrinsicCTWs;
function createActionTransformerCheckers(actionDefDict) {
const checkers = [];
for (const entity in actionDefDict) {
for (const attr in actionDefDict[entity]) {
const def = actionDefDict[entity][attr];
const { stm, is } = def;
for (const action in stm) {
const actionStm = stm[action];
const conditionalFilter = typeof actionStm[0] === 'string' ? {
[attr]: actionStm[0],
} : {
[attr]: {
$in: actionStm[0],
},
};
checkers.push({
action: action,
type: 'row',
entity,
filter: conditionalFilter,
errMsg: '',
});
// 这里用data类型的checker改数据了不太好先这样
checkers.push({
action: action,
type: 'logicalData',
entity,
checker: (operation) => {
const { data } = operation;
if (data instanceof Array) {
data.forEach((d) => Object.assign(d, {
[attr]: stm[action][1],
}));
}
else {
Object.assign(data, {
[attr]: stm[action][1],
});
}
}
});
}
if (is) {
checkers.push({
action: 'create',
type: 'logicalData',
entity,
priority: 10, // 优先级要高先于真正的data检查进行
checker: (operation) => {
const { data } = operation;
if (data instanceof Array) {
data.forEach(ele => {
if (!ele[attr]) {
Object.assign(ele, {
[attr]: is,
});
}
});
}
else {
if (!data[attr]) {
Object.assign(data, {
[attr]: is,
});
}
}
}
});
}
}
}
return checkers;
}
function createAttrUpdateCheckers(schema, attrUpdateMatrix) {
const checkers = [];
for (const entity in attrUpdateMatrix) {
const matrix = attrUpdateMatrix[entity];
const updateAttrs = Object.keys(matrix);
const { actions } = schema[entity];
const updateActions = actions.filter((a) => !action_1.readOnlyActions.concat(['create', 'remove']).includes(a));
/**
* 如果一个entity定义了attrUpdateMatrix则必须严格遵循定义未出现在matrix中的属性不允许更新
*/
const updateChecker = {
entity,
action: updateActions,
type: 'logicalData',
checker({ data, filter, action }, context) {
const attrs = Object.keys(data);
const extras = (0, lodash_1.difference)(attrs, updateAttrs);
if (extras.length > 0) {
throw new types_1.OakAttrCantUpdateException(entity, extras, '更新了不允许的属性');
}
const condition = attrs.map(ele => matrix[ele]);
const actions = condition.map(ele => ele.actions).filter(ele => !!ele);
const filters = condition.map(ele => ele.filter).filter(ele => !!ele);
const a = actions.length > 0 && (0, lodash_1.intersection)(actions.flat());
const f = filters.length > 0 && (0, filter_1.combineFilters)(entity, schema, filters);
if (a) {
if (!a.includes(action)) {
// 找到不满足的那个attr
const attrsIllegal = attrs.filter((attr) => matrix[attr]?.actions && !matrix[attr]?.actions?.includes(action));
throw new types_1.OakAttrCantUpdateException(entity, attrsIllegal, `${attrsIllegal}不允许被${action}动作更新`);
}
}
if (f) {
const result = (0, filter_1.checkFilterContains)(entity, context, f, filter, true);
if (result instanceof Promise) {
return result.then((v) => {
if (!v) {
throw new types_1.OakAttrCantUpdateException(entity, attrs, '更新的行当前属性不满足约束,请仔细检查数据');
}
});
}
if (!result) {
throw new types_1.OakAttrCantUpdateException(entity, attrs, '更新的行当前属性不满足约束,请仔细检查数据');
}
}
}
};
checkers.push(updateChecker);
}
return checkers;
}
function makeIntrinsicCheckers(schema, actionDefDict, attrUpdateMatrix) {
const checkers = [];
checkers.push(...(0, modi_1.createModiRelatedCheckers)(schema));
checkers.push(...(0, checker_1.createRemoveCheckers)(schema));
checkers.push(...(0, checker_1.createCreateCheckers)(schema));
// action状态转换矩阵相应的checker
checkers.push(...createActionTransformerCheckers(actionDefDict));
// unique索引相应的checker
checkers.push(...createUniqueCheckers(schema));
if (attrUpdateMatrix) {
// attrUpdateMatrix相应的checker
checkers.push(...createAttrUpdateCheckers(schema, attrUpdateMatrix));
}
return checkers;
}
exports.makeIntrinsicCheckers = makeIntrinsicCheckers;

View File

@ -1,10 +1,9 @@
import { ActionDictOfEntityDict, BBWatcher, Checker, EntityDict, StorageSchema, Trigger } from "../types";
import { ActionDictOfEntityDict, Checker, EntityDict, StorageSchema, Trigger, Watcher, AttrUpdateMatrix } from "../types";
import { SyncContext } from "./SyncRowStore";
import { AsyncContext } from "./AsyncRowStore";
import { EntityDict as BaseEntityDict } from '../base-app-domain/EntityDict';
export declare function getFullProjection<ED extends EntityDict & BaseEntityDict, T extends keyof ED>(entity: T, schema: StorageSchema<ED>): ED[T]["Selection"]["data"];
export declare function makeIntrinsicCTWs<ED extends EntityDict & BaseEntityDict, Cxt extends AsyncContext<ED>, FrontCxt extends SyncContext<ED>>(schema: StorageSchema<ED>, actionDefDict: ActionDictOfEntityDict<ED>): {
export declare function makeIntrinsicCTWs<ED extends EntityDict & BaseEntityDict, Cxt extends AsyncContext<ED>, FrontCxt extends SyncContext<ED>>(schema: StorageSchema<ED>, actionDefDict: ActionDictOfEntityDict<ED>, attrUpdateMatrix?: AttrUpdateMatrix<ED>): {
triggers: Trigger<ED, keyof ED, Cxt>[];
checkers: Checker<ED, keyof ED, Cxt | FrontCxt>[];
watchers: BBWatcher<ED, keyof ED>[];
watchers: Watcher<ED, keyof ED, Cxt>[];
};

View File

@ -0,0 +1,45 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.makeIntrinsicCTWs = void 0;
const actionAuth_1 = require("./actionAuth");
const modi_1 = require("./modi");
const IntrinsicCheckers_1 = require("./IntrinsicCheckers");
function createExpiredWatchers(schema) {
const watchers = [];
for (const entity in schema) {
const { attributes } = schema[entity];
const { expiresAt, expired } = attributes;
if (expiresAt && expiresAt.type === 'datetime' && expired && expired.type === 'boolean') {
// 如果有定义expiresAt和expired则自动生成一个检查的watcher
watchers.push({
entity,
name: `对象${entity}上的过期自动watcher`,
filter: () => {
return {
expired: false,
expiresAt: {
$lte: Date.now(),
},
};
},
action: 'update',
actionData: {
expired: true,
},
});
}
}
return watchers;
}
function makeIntrinsicCTWs(schema, actionDefDict, attrUpdateMatrix) {
const checkers = (0, IntrinsicCheckers_1.makeIntrinsicCheckers)(schema, actionDefDict, attrUpdateMatrix);
const triggers = (0, modi_1.createModiRelatedTriggers)(schema);
triggers.push(...actionAuth_1.triggers);
const watchers = createExpiredWatchers(schema);
return {
triggers,
checkers,
watchers,
};
}
exports.makeIntrinsicCTWs = makeIntrinsicCTWs;

View File

@ -86,7 +86,6 @@ export declare class RelationAuth<ED extends EntityDict & BaseEntityDict> {
* entity进行actions操作权限的userRelation关系
* @param params
* @param context
* todo paths改成复数以后这里还未充分测试过
*/
export declare function getUserRelationsByActions<ED extends EntityDict & BaseEntityDict, T extends keyof ED, Cxt extends AsyncContext<ED>>(params: {
entity: T;

View File

@ -444,21 +444,7 @@ class RelationAuth {
const { data, filter } = operation;
(0, assert_1.default)(!(data instanceof Array));
if (data) {
const data2 = {};
for (const attr in data) {
const rel = (0, relation_1.judgeRelation)(this.schema, entity, attr);
if (rel === 1) {
// 只需要记住id和各种外键属性不这样处理有些古怪的属性比如coordinate其作为createdata和作为filter并不同构
/* if ((['id', 'entity', 'entityId'].includes(attr) || this.schema[entity].attributes[attr as any]?.type === 'ref') && typeof data[attr] === 'string') {
data2[attr] = data[attr];
} */
// 假设不再成立userEntityGrant需要relationEntity这样的属性
if (!['geometry', 'geography', 'st_geometry', 'st_point'].includes(this.schema[entity].attributes[attr]?.type)) {
data2[attr] = data[attr];
}
}
}
return data2;
return (0, filter_1.translateCreateDataToFilter)(this.schema, entity, data);
}
return filter;
};
@ -1112,7 +1098,6 @@ exports.RelationAuth = RelationAuth;
* 获取有对entity进行actions操作权限的userRelation关系
* @param params
* @param context
* todo paths改成复数以后这里还未充分测试过
*/
async function getUserRelationsByActions(params, context) {
const { entity, filter, actions, overlap } = params;
@ -1186,7 +1171,7 @@ async function getUserRelationsByActions(params, context) {
const userEntities = await Promise.all(directAuths.map(async ({ path }) => {
const { value, recursive } = path;
(0, assert_1.default)(!recursive);
const { getData, projection } = (0, relationPath_1.destructDirectPath)(context.getSchema(), entity, value, recursive);
const { getData, projection } = (0, relationPath_1.destructDirectUserPath)(context.getSchema(), entity, value);
const rows = await context.select(entity, {
data: projection,
filter,

View File

@ -4,6 +4,7 @@ import { Logger } from "../types/Logger";
import { Checker } from '../types/Auth';
import { Trigger, VolatileTrigger } from "../types/Trigger";
import { AsyncContext } from './AsyncRowStore';
import { StorageSchema } from '../types';
/**
* update可能会传入多种不同的actionupdate trigger
*/
@ -17,7 +18,7 @@ export declare class TriggerExecutor<ED extends EntityDict & BaseEntityDict, Cxt
private onVolatileTrigger;
constructor(contextBuilder: (cxtString?: string) => Promise<Cxt>, logger?: Logger, onVolatileTrigger?: <T extends keyof ED>(entity: T, trigger: VolatileTrigger<ED, T, Cxt>, ids: string[], cxtStr: string, option: OperateOption) => Promise<void>);
setOnVolatileTrigger(onVolatileTrigger: <T extends keyof ED>(entity: T, trigger: VolatileTrigger<ED, T, Cxt>, ids: string[], cxtStr: string, option: OperateOption) => Promise<void>): void;
registerChecker<T extends keyof ED>(checker: Checker<ED, T, Cxt>): void;
registerChecker<T extends keyof ED>(checker: Checker<ED, T, Cxt>, schema: StorageSchema<ED>): void;
registerTrigger<T extends keyof ED>(trigger: Trigger<ED, T, Cxt>): void;
unregisterTrigger<T extends keyof ED>(trigger: Trigger<ED, T, Cxt>): void;
private preCommitTrigger;

View File

@ -11,6 +11,7 @@ const SyncRowStore_1 = require("./SyncRowStore");
const checker_1 = require("./checker");
const uuid_1 = require("../utils/uuid");
const action_1 = require("../actions/action");
const types_1 = require("../types");
/**
* update可能会传入多种不同的action此时都需要检查update trigger
*/
@ -53,10 +54,10 @@ class TriggerExecutor {
setOnVolatileTrigger(onVolatileTrigger) {
this.onVolatileTrigger = onVolatileTrigger;
}
registerChecker(checker) {
const { entity, action, type, conditionalFilter, mt } = checker;
registerChecker(checker, schema) {
const { entity, action, type, mt } = checker;
const triggerName = `${String(entity)}${action}权限检查-${this.counter++}`;
const { fn, when } = (0, checker_1.translateCheckerInAsyncContext)(checker);
const { fn, when } = (0, checker_1.translateCheckerInAsyncContext)(checker, schema);
const trigger = {
checkerType: type,
name: triggerName,
@ -66,7 +67,7 @@ class TriggerExecutor {
fn,
when,
mt,
filter: conditionalFilter,
filter: checker.conditionalFilter,
};
this.registerTrigger(trigger);
}
@ -222,15 +223,20 @@ class TriggerExecutor {
if (operation.action === 'create') {
if (data instanceof Array) {
ids = data.map(ele => ele.id);
cxtStr = data[0].$$triggerData$$.cxtStr;
cxtStr = data[0].$$triggerData$$?.cxtStr || await context.toString();
}
else {
ids = [data.id];
cxtStr = data.$$triggerData$$.cxtStr;
cxtStr = data.$$triggerData$$?.cxtStr || await context.toString();
}
}
else {
cxtStr = data.$$triggerData$$.cxtStr;
/**
* 若trigger是makeSure则应使用当时缓存的cxt有可能是checkpoint反复调用
* 若trigger是takeEasy只会在事务提交时做一次使用当前context应也无大问题
* 暂时先这样设计若当前提交事务中改变了cxt内容也许会有问题by Xc 20240319
*/
cxtStr = data.$$triggerData$$?.cxtStr || await context.toString();
const record = opRecords.find(ele => ele.id === operation.id);
// 目前框架在operation时一定会将ids记录在operation当中见CascadeStore中的doUpdateSingleRowAsync函数
(0, assert_1.default)(record && record.a !== 'c');
@ -321,26 +327,24 @@ class TriggerExecutor {
(0, assert_1.default)(trigger && trigger.when === 'commit');
(0, assert_1.default)(ids.length > 0);
const { fn } = trigger;
await fn({ ids }, context, option);
const callback = await fn({ ids }, context, option);
if (trigger.strict === 'makeSure') {
try {
await context.operate(entity, {
id: await (0, uuid_1.generateNewIdAsync)(),
action: 'update',
data: {
[Entity_1.TriggerDataAttribute]: null,
[Entity_1.TriggerUuidAttribute]: null,
},
filter: {
id: {
$in: ids,
}
await context.operate(entity, {
id: await (0, uuid_1.generateNewIdAsync)(),
action: 'update',
data: {
[Entity_1.TriggerDataAttribute]: null,
[Entity_1.TriggerUuidAttribute]: null,
},
filter: {
id: {
$in: ids,
}
}, { includedDeleted: true, blockTrigger: true });
}
catch (err) {
throw err;
}
}
}, { includedDeleted: true, blockTrigger: true });
}
if (typeof callback === 'function') {
await callback(context, option);
}
}
/**
@ -487,7 +491,9 @@ class TriggerExecutor {
}
catch (err) {
await context.rollback();
this.logger.error(`执行checkpoint时出错对象是「${entity}」,异常是`, err);
if (!(err instanceof types_1.OakMakeSureByMySelfException)) {
this.logger.error(`执行checkpoint时出错对象是「${entity}」,异常是`, err);
}
}
}
return result;

View File

@ -8,11 +8,11 @@ import { SyncContext } from './SyncRowStore';
* @param silent silentrow和relation类型的checker只会把限制条件加到查询上create动作
* @returns
*/
export declare function translateCheckerInAsyncContext<ED extends EntityDict & BaseEntityDict, T extends keyof ED, Cxt extends AsyncContext<ED>>(checker: Checker<ED, T, Cxt>): {
export declare function translateCheckerInAsyncContext<ED extends EntityDict & BaseEntityDict, T extends keyof ED, Cxt extends AsyncContext<ED>>(checker: Checker<ED, T, Cxt>, schema: StorageSchema<ED>): {
fn: Trigger<ED, T, Cxt>['fn'];
when: 'before' | 'after';
};
export declare function translateCheckerInSyncContext<ED extends EntityDict & BaseEntityDict, T extends keyof ED, Cxt extends SyncContext<ED>>(checker: Checker<ED, T, Cxt>): {
export declare function translateCheckerInSyncContext<ED extends EntityDict & BaseEntityDict, T extends keyof ED, Cxt extends SyncContext<ED>>(checker: Checker<ED, T, Cxt>, schema: StorageSchema<ED>): {
fn: (operation: ED[T]['Operation'], context: Cxt, option: OperateOption | SelectOption) => void;
when: 'before' | 'after';
};

View File

@ -6,16 +6,28 @@ const assert_1 = tslib_1.__importDefault(require("assert"));
const filter_1 = require("../store/filter");
const Exception_1 = require("../types/Exception");
const types_1 = require("../types");
const actionDef_1 = require("./actionDef");
const lodash_1 = require("../utils/lodash");
const action_1 = require("../actions/action");
function getFullProjection(entity, schema) {
const { attributes } = schema[entity];
const projection = {
id: 1,
$$createAt$$: 1,
$$updateAt$$: 1,
$$deleteAt$$: 1,
};
Object.keys(attributes).forEach((k) => Object.assign(projection, {
[k]: 1,
}));
return projection;
}
/**
*
* @param checker 要翻译的checker
* @param silent 如果silent则row和relation类型的checker只会把限制条件加到查询上而不报错除掉create动作
* @returns
*/
function translateCheckerInAsyncContext(checker) {
function translateCheckerInAsyncContext(checker, schema) {
const { entity, type } = checker;
const when = 'before'; // 现在create的relation改成提前的expression检查了原先是先插入再后检查性能不行而且select也需要实现前检查
switch (type) {
@ -34,74 +46,60 @@ function translateCheckerInAsyncContext(checker) {
case 'row': {
const { filter, errMsg, inconsistentRows } = checker;
const fn = (async ({ operation }, context, option) => {
const { filter: operationFilter, action } = operation;
const { filter: operationFilter, data, action } = operation;
const filter2 = typeof filter === 'function' ? await filter(operation, context, option) : filter;
if (['select', 'count', 'stat'].includes(action)) {
operation.filter = (0, filter_1.combineFilters)(entity, context.getSchema(), [operationFilter, filter2]);
return 0;
}
else {
if (await (0, filter_1.checkFilterContains)(entity, context, filter2, operationFilter || {}, true)) {
return 0;
}
if (inconsistentRows) {
const { entity: entity2, selection: selection2 } = inconsistentRows;
const rows2 = await context.select(entity2, selection2(operationFilter), {
dontCollect: true,
blockTrigger: true,
});
const e = new Exception_1.OakRowInconsistencyException(undefined, errMsg);
e.addData(entity2, rows2);
throw e;
}
else {
const rows2 = await context.select(entity, {
data: (0, actionDef_1.getFullProjection)(entity, context.getSchema()),
filter: Object.assign({}, operationFilter, {
$not: filter2,
})
}, {
dontCollect: true,
blockTrigger: true,
});
const e = new Exception_1.OakRowInconsistencyException(undefined, errMsg);
e.addData(entity, rows2);
throw e;
}
}
});
return {
fn,
when,
};
}
case 'relation': {
const { relationFilter, errMsg } = checker;
const fn = (async ({ operation }, context, option) => {
if (context.isRoot()) {
return 0;
}
// assert(operation.action !== 'create', `${entity as string}上的create动作定义了relation类型的checker,请使用expressionRelation替代`);
// 对后台而言将生成的relationFilter加到filter之上(select可以在此加以权限的过滤)
const result = typeof relationFilter === 'function' ? await relationFilter(operation, context, option) : relationFilter;
if (result) {
const { filter, action } = operation;
const checkSingle = async (f) => {
if (await (0, filter_1.checkFilterContains)(entity, context, filter2, f, true)) {
return;
}
if (inconsistentRows) {
const { entity: entity2, selection: selection2 } = inconsistentRows;
const rows2 = await context.select(entity2, selection2(operationFilter), {
dontCollect: true,
blockTrigger: true,
});
const e = new Exception_1.OakRowInconsistencyException(undefined, errMsg);
e.addData(entity2, rows2);
throw e;
}
else {
const rows2 = await context.select(entity, {
data: getFullProjection(entity, context.getSchema()),
filter: Object.assign({}, operationFilter, {
$not: filter2,
})
}, {
dontCollect: true,
blockTrigger: true,
});
const e = new Exception_1.OakRowInconsistencyException(undefined, errMsg);
e.addData(entity, rows2);
throw e;
}
};
let operationFilter2 = operationFilter;
if (action === 'create') {
console.warn(`${entity}对象的create类型的checker中存在无法转换为表达式形式的情况请尽量使用authDef格式定义这类checker`);
return 0;
}
if (['select', 'count', 'stat'].includes(action)) {
operation.filter = (0, filter_1.combineFilters)(entity, context.getSchema(), [filter, result]);
return 0;
}
(0, assert_1.default)(filter);
if (await (0, filter_1.checkFilterContains)(entity, context, result, filter, true)) {
// 后台进行创建检查时以传入的data为准
(0, assert_1.default)(data);
if (data instanceof Array) {
for (const d of data) {
await checkSingle((0, filter_1.translateCreateDataToFilter)(schema, entity, d));
}
}
else {
await checkSingle((0, filter_1.translateCreateDataToFilter)(schema, entity, data));
}
return;
}
const errMsg2 = typeof errMsg === 'function' ? errMsg(operation, context, option) : errMsg;
throw new Exception_1.OakUserUnpermittedException(entity, operation, errMsg2);
(0, assert_1.default)(operationFilter2, 'row类型的checker遇到了操作的filter未定义');
await checkSingle(operationFilter2);
return 0;
}
return 0;
});
return {
fn,
@ -109,13 +107,9 @@ function translateCheckerInAsyncContext(checker) {
};
}
case 'logical':
case 'logicalRelation':
case 'logicalData': {
const { checker: checkerFn } = checker;
const fn = (async ({ operation }, context, option) => {
if (context.isRoot() && type === 'logicalRelation') {
return 0;
}
await checkerFn(operation, context, option);
return 0;
});
@ -130,7 +124,7 @@ function translateCheckerInAsyncContext(checker) {
}
}
exports.translateCheckerInAsyncContext = translateCheckerInAsyncContext;
function translateCheckerInSyncContext(checker) {
function translateCheckerInSyncContext(checker, schema) {
const { entity, type } = checker;
const when = 'before'; // 现在create的relation改成提前的expression检查了原先是先插入再后检查性能不行而且select也需要实现前检查
switch (type) {
@ -143,13 +137,22 @@ function translateCheckerInSyncContext(checker) {
};
}
case 'row': {
const { filter, errMsg } = checker;
const { filter, errMsg, entity } = checker;
const fn = (operation, context, option) => {
const { filter: operationFilter, action } = operation;
const { filter: operationFilter, data, action } = operation;
const filter2 = typeof filter === 'function' ? filter(operation, context, option) : filter;
(0, assert_1.default)(operationFilter);
let operationFilter2 = operationFilter;
if (action === 'create') {
if (data) {
// 前端的策略是有data用data无data用filter
// 目前前端应该不可能制造出来createMultiple
(0, assert_1.default)(!(data instanceof Array));
operationFilter2 = (0, filter_1.translateCreateDataToFilter)(schema, entity, data);
}
}
(0, assert_1.default)(!(filter2 instanceof Promise));
if ((0, filter_1.checkFilterContains)(entity, context, filter2, operationFilter, true)) {
(0, assert_1.default)(operationFilter2, '定义了row类型的checker但却进行了无filter操作');
if ((0, filter_1.checkFilterContains)(entity, context, filter2, operationFilter2, true)) {
return;
}
const e = new Exception_1.OakRowInconsistencyException(undefined, errMsg || 'row checker condition illegal');
@ -160,41 +163,10 @@ function translateCheckerInSyncContext(checker) {
when,
};
}
case 'relation': {
const { relationFilter, errMsg } = checker;
const fn = (operation, context, option) => {
if (context.isRoot()) {
return;
}
const result = typeof relationFilter === 'function' ? relationFilter(operation, context, option) : relationFilter;
(0, assert_1.default)(!(result instanceof Promise));
if (result) {
const { filter, action } = operation;
if (action === 'create') {
console.warn(`${entity}对象的create类型的checker中存在无法转换为表达式形式的情况请尽量使用authDef格式定义这类checker`);
return;
}
(0, assert_1.default)(filter);
if ((0, filter_1.checkFilterContains)(entity, context, result, filter, true)) {
return;
}
const errMsg2 = typeof errMsg === 'function' ? errMsg(operation, context, option) : errMsg;
throw new Exception_1.OakUserUnpermittedException(entity, operation, errMsg2);
}
};
return {
fn,
when,
};
}
case 'logical':
case 'logicalRelation':
case 'logicalData': {
const { checker: checkerFn } = checker;
const fn = (operation, context, option) => {
if (context.isRoot() && type === 'logicalRelation') {
return;
}
checkerFn(operation, context, option);
};
return {

View File

@ -2,6 +2,7 @@ import { EntityDict as BaseEntityDict, StorageSchema } from '../types';
import { EntityDict } from "../base-app-domain";
import { AsyncContext } from './AsyncRowStore';
import { SyncContext } from './SyncRowStore';
export declare function translateCreateDataToFilter<ED extends EntityDict & BaseEntityDict, T extends keyof ED>(schema: StorageSchema<ED>, entity: T, data: ED[T]['CreateSingle']['data']): ED[T]["Selection"]["filter"];
export declare function combineFilters<ED extends EntityDict & BaseEntityDict, T extends keyof ED>(entity: T, schema: StorageSchema<ED>, filters: Array<ED[T]['Selection']['filter']>, union?: true): ED[T]["Selection"]["filter"] | undefined;
/**
* //filter在逻辑上相容或者相斥

View File

@ -1,34 +1,25 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.translateFilterToObjectPredicate = exports.checkFilterRepel = exports.checkFilterContains = exports.makeTreeDescendantFilter = exports.makeTreeAncestorFilter = exports.same = exports.getRelevantIds = exports.judgeValueRelation = exports.combineFilters = void 0;
exports.translateFilterToObjectPredicate = exports.checkFilterRepel = exports.checkFilterContains = exports.makeTreeDescendantFilter = exports.makeTreeAncestorFilter = exports.same = exports.getRelevantIds = exports.judgeValueRelation = exports.combineFilters = exports.translateCreateDataToFilter = void 0;
const tslib_1 = require("tslib");
const assert_1 = tslib_1.__importDefault(require("assert"));
const types_1 = require("../types");
const lodash_1 = require("../utils/lodash");
const relation_1 = require("./relation");
/* function getFilterAttributes(filter: Record<string, any>) {
const attributes = [] as string[];
for (const attr in filter) {
if (attr.startsWith('$') || attr.startsWith('#')) {
if (['$and', '$or'].includes(attr)) {
for (const f of filter[attr]) {
const a = getFilterAttributes(f);
attributes.push(...a);
}
function translateCreateDataToFilter(schema, entity, data) {
const data2 = {};
for (const attr in data) {
const rel = (0, relation_1.judgeRelation)(schema, entity, attr);
if (rel === 1) {
// 只需要记住id和各种外键属性不这样处理有些古怪的属性比如coordinate其作为createdata和作为filter并不同构
if (!['geometry', 'geography', 'st_geometry', 'st_point'].includes(schema[entity].attributes[attr]?.type)) {
data2[attr] = data[attr];
}
else if (attr === '$not') {
const a = getFilterAttributes(filter[attr]);
attributes.push(...a);
}
}
else {
attributes.push(attr);
}
}
return uniq(attributes);
} */
return data2;
}
exports.translateCreateDataToFilter = translateCreateDataToFilter;
/**
* 尽量合并外键的连接防止在数据库中join的对象过多
* @param entity

View File

@ -1,5 +0,0 @@
import { EntityDict as BaseEntityDict } from '../base-app-domain';
import { StorageSchema, EntityDict, Trigger } from '../types';
import { AsyncContext } from '../store/AsyncRowStore';
import { SyncContext } from '../store/SyncRowStore';
export declare function createDynamicTriggers<ED extends EntityDict & BaseEntityDict, Cxt extends AsyncContext<ED> | SyncContext<ED>>(schema: StorageSchema<ED>): Trigger<ED, keyof ED, Cxt>[];

View File

@ -1,26 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.createDynamicTriggers = void 0;
const modi_1 = require("../store/modi");
/* function createOperTriggers<ED extends EntityDict & BaseEntityDict, Cxt extends AsyncContext<ED> | SyncContext<ED>>() {
return [
{
name: 'assign initial bornAt for local oper',
entity: 'oper',
action: 'create',
when: 'before',
fn({ operation }) {
const { data } = operation;
assert(!(data instanceof Array));
if (!data.bornAt) {
data.bornAt = Date.now();
}
return 1;
}
} as CreateTrigger<ED, 'oper', Cxt>
] as Trigger<ED, keyof ED, Cxt>[];
} */
function createDynamicTriggers(schema) {
return (0, modi_1.createModiRelatedTriggers)(schema);
}
exports.createDynamicTriggers = createDynamicTriggers;

23
lib/types/Auth.d.ts vendored
View File

@ -3,7 +3,7 @@ import { AsyncContext } from "../store/AsyncRowStore";
import { SyncContext } from "../store/SyncRowStore";
import { EntityDict, OperateOption, SelectOption } from "../types/Entity";
import { ModiTurn } from './Trigger';
export type CheckerType = 'relation' | 'row' | 'data' | 'logical' | 'logicalRelation' | 'logicalData';
export type CheckerType = 'row' | 'data' | 'logical' | 'logicalData';
/**
* conditionalFilter是指该action发生时operation所操作的行中有满足conditionalFilter的行
* trigger的filter条件trigger中的说明
@ -14,15 +14,14 @@ export type DataChecker<ED extends EntityDict, T extends keyof ED, Cxt extends A
entity: T;
mt?: ModiTurn;
action: Omit<ED[T]['Action'], 'remove'> | Array<Omit<ED[T]['Action'], 'remove'>>;
checker: (data: ED[T]['Create']['data'] | ED[T]['Update']['data'], context: Cxt) => SyncOrAsync<any>;
conditionalFilter?: ED[T]['Update']['filter'] | ((operation: ED[T]['Operation'], context: Cxt, option: OperateOption) => SyncOrAsync<ED[T]['Selection']['filter']>);
checker: (data: Readonly<ED[T]['Create']['data'] | ED[T]['Update']['data']>, context: Cxt) => SyncOrAsync<any>;
};
export type RowChecker<ED extends EntityDict, T extends keyof ED, Cxt extends AsyncContext<ED> | SyncContext<ED>> = {
priority?: number;
type: 'row';
entity: T;
mt?: ModiTurn;
action: Omit<ED[T]['Action'], 'create'> | Array<Omit<ED[T]['Action'], 'create'>>;
action: ED[T]['Action'] | Array<ED[T]['Action']>;
filter: ED[T]['Selection']['filter'] | ((operation: ED[T]['Operation'] | ED[T]['Selection'], context: Cxt, option: OperateOption | SelectOption) => SyncOrAsync<ED[T]['Selection']['filter']>);
errMsg?: string;
inconsistentRows?: {
@ -31,28 +30,16 @@ export type RowChecker<ED extends EntityDict, T extends keyof ED, Cxt extends As
};
conditionalFilter?: ED[T]['Update']['filter'] | ((operation: ED[T]['Operation'], context: Cxt, option: OperateOption) => SyncOrAsync<ED[T]['Update']['filter']>);
};
export type RelationChecker<ED extends EntityDict, T extends keyof ED, Cxt extends AsyncContext<ED> | SyncContext<ED>> = {
priority?: number;
type: 'relation';
entity: T;
mt?: ModiTurn;
when?: 'after';
action: ED[T]['Action'] | Array<ED[T]['Action']>;
relationFilter: (operation: ED[T]['Operation'] | ED[T]['Selection'], context: Cxt, option: OperateOption | SelectOption) => SyncOrAsync<ED[T]['Selection']['filter']>;
errMsg: string | ((operation: ED[T]['Operation'] | ED[T]['Selection'], context: Cxt, option?: OperateOption | SelectOption) => string);
conditionalFilter?: ED[T]['Update']['filter'] | ((operation: ED[T]['Operation'], context: Cxt, option: OperateOption) => SyncOrAsync<ED[T]['Selection']['filter']>);
};
export type LogicalChecker<ED extends EntityDict, T extends keyof ED, Cxt extends AsyncContext<ED> | SyncContext<ED>> = {
priority?: number;
type: 'logical' | 'logicalData' | 'logicalRelation';
when?: 'after';
type: 'logical' | 'logicalData';
mt?: ModiTurn;
entity: T;
action: ED[T]['Action'] | Array<ED[T]['Action']>;
checker: (operation: ED[T]['Operation'] | ED[T]['Selection'], context: Cxt, option: OperateOption | SelectOption) => SyncOrAsync<any>;
conditionalFilter?: ED[T]['Update']['filter'] | ((operation: ED[T]['Operation'], context: Cxt, option: OperateOption) => SyncOrAsync<ED[T]['Update']['filter']>);
};
export type Checker<ED extends EntityDict, T extends keyof ED, Cxt extends AsyncContext<ED> | SyncContext<ED>> = DataChecker<ED, T, Cxt> | RowChecker<ED, T, Cxt> | RelationChecker<ED, T, Cxt> | LogicalChecker<ED, T, Cxt>;
export type Checker<ED extends EntityDict, T extends keyof ED, Cxt extends AsyncContext<ED> | SyncContext<ED>> = DataChecker<ED, T, Cxt> | RowChecker<ED, T, Cxt> | LogicalChecker<ED, T, Cxt>;
export type AuthDef<ED extends EntityDict, T extends keyof ED> = {
relationAuth?: CascadeRelationAuth<NonNullable<ED[T]['Relation']>>;
actionAuth?: CascadeActionAuth<ED[T]['Action']>;

View File

@ -1,9 +1,17 @@
import { LocaleDef } from './Locale';
import { Index } from './Storage';
import { EntityShape, Configuration } from './Entity';
import { EntityShape, Configuration, EntityDict } from './Entity';
export type EntityDesc<Schema extends EntityShape, Action extends string = '', Relation extends string = '', V extends Record<string, string> = {}> = {
locales: LocaleDef<Schema, Action, Relation, V>;
indexes?: Index<Schema>[];
configuration?: Configuration;
recursiveDepth?: number;
};
export type AttrUpdateMatrix<ED extends EntityDict> = {
[T in keyof ED]?: {
[A in keyof ED[T]['Update']['data']]?: {
actions?: ED[T]['Action'][];
filter?: NonNullable<ED[T]['Selection']['filter']>;
};
};
};

View File

@ -6,6 +6,8 @@ export declare class OakException<ED extends EntityDict> extends Error {
setOpRecords(opRecord: SelectOpResult<ED>): void;
toString(): string;
}
export declare class OakMakeSureByMySelfException<ED extends EntityDict> extends OakException<ED> {
}
export declare class OakDataException<ED extends EntityDict> extends OakException<ED> {
}
export declare class OakUniqueViolationException<ED extends EntityDict> extends OakException<ED> {
@ -81,6 +83,12 @@ export declare class OakInputIllegalException<ED extends EntityDict> extends Oak
export declare class OakAttrNotNullException<ED extends EntityDict> extends OakInputIllegalException<ED> {
constructor(entity: keyof ED, attributes: string[], message?: string);
}
/**
* update时对应属性的露出
*/
export declare class OakAttrCantUpdateException<ED extends EntityDict> extends OakInputIllegalException<ED> {
constructor(entity: keyof ED, attributes: string[], message?: string);
}
/**
*
*/
@ -152,4 +160,4 @@ export declare function makeException<ED extends EntityDict>(data: {
message?: string;
opRecords: SelectOpResult<ED>;
[A: string]: any;
}): OakException<EntityDict> | undefined;
}): OakException<ED> | undefined;

View File

@ -1,6 +1,6 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.makeException = exports.OakExternalException = exports.OakPreConditionUnsetException = exports.OakDeadlock = exports.OakCongruentRowExists = exports.OakRowLockedException = exports.OakUnloggedInException = exports.OakUserInvisibleException = exports.OakUserUnpermittedException = exports.OakAttrNotNullException = exports.OakInputIllegalException = exports.OakRowInconsistencyException = exports.OakServerProxyException = exports.OakNetworkException = exports.OakUserException = exports.OakRowUnexistedException = exports.OakOperExistedException = exports.OakNoRelationDefException = exports.OakImportDataParseException = exports.OakUniqueViolationException = exports.OakDataException = exports.OakException = void 0;
exports.makeException = exports.OakExternalException = exports.OakPreConditionUnsetException = exports.OakDeadlock = exports.OakCongruentRowExists = exports.OakRowLockedException = exports.OakUnloggedInException = exports.OakUserInvisibleException = exports.OakUserUnpermittedException = exports.OakAttrCantUpdateException = exports.OakAttrNotNullException = exports.OakInputIllegalException = exports.OakRowInconsistencyException = exports.OakServerProxyException = exports.OakNetworkException = exports.OakUserException = exports.OakRowUnexistedException = exports.OakOperExistedException = exports.OakNoRelationDefException = exports.OakImportDataParseException = exports.OakUniqueViolationException = exports.OakDataException = exports.OakMakeSureByMySelfException = exports.OakException = void 0;
const tslib_1 = require("tslib");
const assert_1 = tslib_1.__importDefault(require("assert"));
class OakException extends Error {
@ -50,6 +50,10 @@ class OakException extends Error {
}
}
exports.OakException = OakException;
// 这个异常表示模块自己处理跨事务一致性框架pass在分布式数据传递时会用到
class OakMakeSureByMySelfException extends OakException {
}
exports.OakMakeSureByMySelfException = OakMakeSureByMySelfException;
class OakDataException extends OakException {
}
exports.OakDataException = OakDataException;
@ -180,10 +184,19 @@ exports.OakInputIllegalException = OakInputIllegalException;
*/
class OakAttrNotNullException extends OakInputIllegalException {
constructor(entity, attributes, message) {
super(entity, attributes, message || '属性不允许为空');
super(entity, attributes, message || `属性[${attributes.join(',')}]不允许为空`);
}
}
exports.OakAttrNotNullException = OakAttrNotNullException;
/**
* 属性不允许更新抛的异常前端可以用这个异常来处理update时对应属性的露出
*/
class OakAttrCantUpdateException extends OakInputIllegalException {
constructor(entity, attributes, message) {
super(entity, attributes, message || `属性[${attributes.join(',')}]不允许更新`);
}
}
exports.OakAttrCantUpdateException = OakAttrCantUpdateException;
/**
* 用户权限不够时抛的异常
*/
@ -331,106 +344,98 @@ class OakExternalException extends OakUserException {
exports.OakExternalException = OakExternalException;
function makeException(data) {
const { name } = data;
let e = undefined;
switch (name) {
case 'OakException': {
const e = new OakException(data.message);
e.setOpRecords(data.opRecords);
return e;
e = new OakException(data.message);
break;
}
case 'OakUserException': {
const e = new OakUserException(data.message);
e.setOpRecords(data.opRecords);
return e;
break;
}
case 'OakRowInconsistencyException': {
const e = new OakRowInconsistencyException(data.data, data.message);
e.setOpRecords(data.opRecords);
return e;
break;
}
case 'OakInputIllegalException': {
const e = new OakInputIllegalException(data.entity, data.attributes, data.message);
e.setOpRecords(data.opRecords);
return e;
break;
}
case 'OakAttrCantUpdateException': {
const e = new OakAttrCantUpdateException(data.entity, data.attributes, data.message);
break;
}
case 'OakUserUnpermittedException': {
const e = new OakUserUnpermittedException(data.entity, data.operation, data.message);
e.setOpRecords(data.opRecords);
return e;
break;
}
case 'OakUserInvisibleException': {
const e = new OakUserInvisibleException(data.entity, data.operation, data.message);
e.setOpRecords(data.opRecords);
return e;
break;
}
case 'OakUnloggedInException': {
const e = new OakUnloggedInException(data.message);
e.setOpRecords(data.opRecords);
return e;
break;
}
case 'OakCongruentRowExists': {
const e = new OakCongruentRowExists(data.entity, data.data, data.message);
e.setOpRecords(data.opRecords);
return e;
break;
}
case 'OakRowLockedException': {
const e = new OakRowLockedException(data.message);
e.setOpRecords(data.opRecords);
return e;
break;
}
case 'OakRowUnexistedException': {
const e = new OakRowUnexistedException(data.rows);
e.setOpRecords(data.opRecords);
return e;
break;
}
case 'OakDeadlock': {
const e = new OakDeadlock(data.message);
e.setOpRecords(data.opRecords);
return e;
break;
}
case 'OakDataException': {
const e = new OakDataException(data.message);
e.setOpRecords(data.opRecords);
return e;
break;
}
case 'OakNoRelationDefException': {
const e = new OakNoRelationDefException(data.entity, data.action, data.message);
e.setOpRecords(data.opRecords);
return e;
break;
}
case 'OakUniqueViolationException': {
const e = new OakUniqueViolationException(data.rows, data.message);
e.setOpRecords(data.opRecords);
return e;
break;
}
case 'OakImportDataParseException': {
const e = new OakImportDataParseException(data.message, data.line, data.header);
e.setOpRecords(data.opRecords);
return e;
break;
}
case 'OakPreConditionUnsetException': {
const e = new OakPreConditionUnsetException(data.message, data.entity, data.code);
e.setOpRecords(data.opRecords);
return e;
break;
}
case 'OakAttrNotNullException': {
const e = new OakAttrNotNullException(data.entity, data.attributes, data.message);
e.setOpRecords(data.opRecords);
return e;
break;
}
case 'OakExternalException': {
const e = new OakExternalException(data.source, data.code, data.message, data.data);
return e;
break;
}
case 'OakNetworkException': {
const e = new OakNetworkException(data.message);
return e;
break;
}
case 'OakServerProxyException': {
const e = new OakServerProxyException(data.message);
return e;
break;
}
default:
return;
}
if (e) {
e.setOpRecords(data.opRecords);
return e;
}
}
exports.makeException = makeException;

5
lib/types/Sync.d.ts vendored
View File

@ -29,7 +29,8 @@ export interface PullEntityDef<ED extends EntityDict & BaseEntityDict, T extends
export interface PushEntityDef<ED extends EntityDict & BaseEntityDict, T extends keyof ED, Cxt extends AsyncContext<ED>> {
direction: 'push';
entity: T;
path: string;
pathToRemoteEntity: string;
pathToSelfEntity: string;
recursive?: boolean;
relationName?: string;
actions?: ED[T]['Action'][];
@ -65,7 +66,7 @@ export interface SyncSelfConfigBase<ED extends EntityDict & BaseEntityDict> {
entity: keyof ED;
}
interface SyncSelfConfig<ED extends EntityDict & BaseEntityDict, Cxt extends AsyncContext<ED>> extends SyncSelfConfigBase<ED> {
getSelfEncryptInfo: (context: Cxt) => Promise<SelfEncryptInfo>;
getSelfEncryptInfo: (context: Cxt, selfEntityId: string) => Promise<SelfEncryptInfo>;
}
export interface SyncConfig<ED extends EntityDict & BaseEntityDict, Cxt extends AsyncContext<ED>> {
self: SyncSelfConfig<ED, Cxt>;

View File

@ -13,7 +13,8 @@ export declare const TRIGGER_DEFAULT_PRIORITY = 25;
export declare const TRIGGER_MAX_PRIORITY = 50;
export declare const CHECKER_MAX_PRIORITY = 99;
/**
* logical可能会更改row和data的值data和row不能修改相关的值priority小一点以确保安全
* logical可能会更改row和data的值data和row不能修改相关的值
* logicalData去改data中的值
*/
export declare const CHECKER_PRIORITY_MAP: Record<CheckerType, number>;
interface TriggerBase<ED extends EntityDict, T extends keyof ED> {
@ -39,7 +40,7 @@ interface TriggerCrossTxn<ED extends EntityDict, Cxt extends AsyncContext<ED> |
cs?: true;
fn: (event: {
ids: string[];
}, context: Cxt, option: OperateOption) => Promise<number> | number;
}, context: Cxt, option: OperateOption) => Promise<((context: Cxt, option: OperateOption) => Promise<any>) | void>;
}
export interface CreateTriggerCrossTxn<ED extends EntityDict, T extends keyof ED, Cxt extends AsyncContext<ED> | SyncContext<ED>> extends CreateTriggerBase<ED, T, Cxt>, TriggerCrossTxn<ED, Cxt> {
}

View File

@ -9,15 +9,14 @@ exports.TRIGGER_DEFAULT_PRIORITY = 25;
exports.TRIGGER_MAX_PRIORITY = 50;
exports.CHECKER_MAX_PRIORITY = 99;
/**
* logical可能会更改row和data的值应当最先执行data和row不能修改相关的值如果要修改手动置priority小一点以确保安全
* logical可能会更改row和data的值应当最先执行data和row不能修改相关的值
* 允许logicalData去改data中的值
*/
exports.CHECKER_PRIORITY_MAP = {
logicalData: 31,
logical: 33,
row: 51,
data: 61,
logicalData: 61,
relation: 71,
logicalRelation: 71,
};
;
;

View File

@ -1,3 +1,4 @@
/// <reference types="node" />
/**
* assert打包体积过大
*/

View File

@ -14,14 +14,13 @@ export declare function destructRelationPath<ED extends EntityDict & BaseEntityD
getData: (d: Partial<ED[T]['Schema']>) => ED['userRelation']['Schema'][] | undefined;
};
/**
* entity的相对pathuserId
* entity的相对pathuser对象
* @param schema
* @param entity
* @param path
* @param recursive
* @param path path的最后一项一定指向user'aa.bb.cc.dd.user'
* @returns
*/
export declare function destructDirectPath<ED extends EntityDict & BaseEntityDict, T extends keyof ED>(schema: StorageSchema<ED>, entity: T, path: string, recursive?: boolean): {
export declare function destructDirectUserPath<ED extends EntityDict & BaseEntityDict, T extends keyof ED>(schema: StorageSchema<ED>, entity: T, path: string): {
projection: ED[T]['Selection']['data'];
getData: (d: Partial<ED[T]['Schema']>) => {
entity: keyof ED;
@ -29,3 +28,17 @@ export declare function destructDirectPath<ED extends EntityDict & BaseEntityDic
userId: string;
}[] | undefined;
};
/**
* entity的相对path
* @param schema
* @param entity
* @param path
* @returns
*/
export declare function destructDirectPath<ED extends EntityDict & BaseEntityDict, T extends keyof ED>(schema: StorageSchema<ED>, entity: T, path: string): {
projection: ED[T]['Selection']['data'];
getData: (d: Partial<ED[keyof ED]['Schema']>, path2?: string) => {
entity: keyof ED;
data: Partial<ED[keyof ED]['Schema']>;
}[] | undefined;
};

View File

@ -1,6 +1,6 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.destructDirectPath = exports.destructRelationPath = void 0;
exports.destructDirectPath = exports.destructDirectUserPath = exports.destructRelationPath = void 0;
const tslib_1 = require("tslib");
const assert_1 = tslib_1.__importDefault(require("assert"));
const relation_1 = require("../store/relation");
@ -60,7 +60,7 @@ function destructRelationPath(schema, entity, path, relationFilter, recursive) {
},
filter: relationFilter,
} // as ED['userRelation']['Selection']
},
}, // as ED[keyof ED]['Selection']['data'],
getData: (d) => {
return d.userRelation$entity;
},
@ -108,15 +108,38 @@ function destructRelationPath(schema, entity, path, relationFilter, recursive) {
}
exports.destructRelationPath = destructRelationPath;
/**
* 根据entity的相对path找到对应的根结点对象上的直接userId
* 根据entity的相对path找到其根结点以及相应的user对象
* @param schema
* @param entity
* @param path path的最后一项一定指向user'aa.bb.cc.dd.user'
* @returns
*/
function destructDirectUserPath(schema, entity, path) {
const paths = path.split('.');
const last = paths.pop();
const path2 = paths.join('.');
const { projection, getData } = destructDirectPath(schema, entity, path);
return {
projection,
getData: (d) => {
const userInfo = getData(d, path2);
return userInfo?.map(({ entity, data }) => ({
entity,
entityId: data.id,
userId: (data[`${last}Id`] || data.entityId)
}));
}
};
}
exports.destructDirectUserPath = destructDirectUserPath;
/**
* 根据entity的相对path找到对应的根结点对象数据行
* @param schema
* @param entity
* @param path
* @param recursive
* @returns
*/
function destructDirectPath(schema, entity, path, recursive) {
(0, assert_1.default)(!recursive, '直接对象上不可能有recursive');
function destructDirectPath(schema, entity, path) {
(0, assert_1.default)(path, '直接对象的路径最终要指向user对象不可能为空');
const paths = path.split('.');
const makeIter = (e, idx) => {
@ -124,37 +147,51 @@ function destructDirectPath(schema, entity, path, recursive) {
const rel = (0, relation_1.judgeRelation)(schema, e, attr);
if (idx === paths.length - 1) {
if (rel === 2) {
(0, assert_1.default)(attr === 'user');
return {
projection: {
id: 1,
entity: 1,
entityId: 1,
},
getData: (d) => {
getData: (d, p) => {
if (d) {
if (!p) {
return [{
entity: e,
data: d,
}];
}
(0, assert_1.default)(p === attr);
return [{
entity: e,
entityId: d.id,
userId: d.entityId,
entity: attr,
data: {
id: d.entityId,
},
}];
}
},
};
}
else {
(0, assert_1.default)(rel === 'user');
return {
projection: {
id: 1,
[`${attr}Id`]: 1,
},
getData: (d) => {
getData: (d, p) => {
if (d) {
if (!p) {
return [{
entity: e,
data: d,
}];
}
(0, assert_1.default)(p === attr);
return [{
entity: e,
entityId: d.id,
userId: d[`${attr}Id`],
entity: rel,
data: {
id: d[`${attr}Id`],
},
}];
}
},
@ -168,7 +205,19 @@ function destructDirectPath(schema, entity, path, recursive) {
id: 1,
[attr]: projection,
},
getData: (d) => d[attr] && getData(d[attr]),
getData: (d, p) => {
if (d) {
if (!p) {
return [{
entity: e,
data: d,
}];
}
const ps = p.split('.');
(0, assert_1.default)(ps[0] === attr);
return d[attr] && getData(d[attr], ps.slice(1).join('.'));
}
},
};
}
else if (typeof rel === 'string') {
@ -178,7 +227,19 @@ function destructDirectPath(schema, entity, path, recursive) {
id: 1,
[attr]: projection,
},
getData: (d) => d[attr] && getData(d[attr]),
getData: (d, p) => {
if (d) {
if (!p) {
return [{
entity: e,
data: d,
}];
}
const ps = p.split('.');
(0, assert_1.default)(ps[0] === attr);
return d[attr] && getData(d[attr], ps.slice(1).join('.'));
}
},
};
}
else {
@ -193,7 +254,17 @@ function destructDirectPath(schema, entity, path, recursive) {
data: projection,
},
},
getData: (d) => d[attr] && d[attr].map(ele => getData(ele)).flat().filter(ele => !!ele),
getData: (d, p) => {
if (!p) {
return [{
entity: e,
data: d,
}];
}
const ps = p.split('.');
(0, assert_1.default)(ps[0] === attr);
return d[attr] && d[attr].map(ele => getData(ele, ps.slice(1).join('.'))).flat().filter(ele => !!ele);
}
};
}
};

View File

@ -1,6 +1,6 @@
{
"name": "oak-domain",
"version": "4.2.8",
"version": "4.4.0",
"author": {
"name": "XuChang"
},

View File

@ -1,30 +0,0 @@
import { CascadeRelationItem, RelationHierarchy, EntityDict } from "../types/Entity";
export type GenericRelation = 'owner';
export function convertHierarchyToAuth<ED extends EntityDict, T extends keyof ED>(entity: T, hierarchy: RelationHierarchy<NonNullable<ED[T]['Relation']>>): {
[K in NonNullable<ED[T]['Relation']>]?: CascadeRelationItem;
} {
const reverseHierarchy: RelationHierarchy<NonNullable<ED[T]['Relation']>> = {};
for (const r in hierarchy) {
for (const r2 of hierarchy[r as NonNullable<ED[T]['Relation']>]!) {
if (reverseHierarchy[r2]) {
reverseHierarchy[r2]?.push(r as NonNullable<ED[T]['Relation']>);
}
else {
reverseHierarchy[r2] = [r as NonNullable<ED[T]['Relation']>];
}
}
}
const result: {
[K in NonNullable<ED[T]['Relation']>]?: CascadeRelationItem;
} = {};
for (const r in reverseHierarchy) {
result[r as NonNullable<ED[T]['Relation']>] = {
cascadePath: '',
relations: reverseHierarchy[r as NonNullable<ED[T]['Relation']>],
};
}
return result;
}

View File

@ -1,14 +0,0 @@
import { EntityDict } from '../base-app-domain';
import { AsyncContext } from '../store/AsyncRowStore';
import { createRemoveCheckers, createCreateCheckers } from '../store/checker';
import { createModiRelatedCheckers } from '../store/modi';
import { SyncContext } from '../store/SyncRowStore';
import { StorageSchema, EntityDict as BaseEntityDict, Checker } from '../types';
export function createDynamicCheckers<ED extends EntityDict & BaseEntityDict, Cxt extends AsyncContext<ED> | SyncContext<ED>>(schema: StorageSchema<ED>) {
const checkers: Checker<ED, keyof ED, Cxt>[] = [];
checkers.push(...createModiRelatedCheckers<ED, Cxt>(schema));
checkers.push(...createRemoveCheckers<ED, Cxt>(schema));
checkers.push(...createCreateCheckers<ED, Cxt>(schema));
return checkers;
}

View File

@ -10,7 +10,7 @@ export interface Schema extends EntityShape {
extra?: Object;
operator?: User;
targetEntity: String<32>;
bornAt: Datetime;
bornAt?: Datetime;
};
const entityDesc: EntityDesc<Schema> = {

View File

@ -9,7 +9,7 @@ import { StorageSchema } from '../types/Storage';
import { combineFilters } from "./filter";
import { judgeRelation } from "./relation";
import { EXPRESSION_PREFIX, getAttrRefInExpression, OakRowUnexistedException } from "../types";
import { unset, uniq, cloneDeep, pick } from '../utils/lodash';
import { unset, uniq, cloneDeep, pick, difference } from '../utils/lodash';
import { SyncContext } from "./SyncRowStore";
import { AsyncContext } from "./AsyncRowStore";
import { getRelevantIds } from "./filter";
@ -526,7 +526,7 @@ export abstract class CascadeStore<ED extends EntityDict & BaseEntityDict> exten
data: projection2[attr],
filter: {
id: {
$in: entityIds
$in: difference(entityIds, subRows.map(ele => ele.id!)),
},
},
},
@ -635,7 +635,7 @@ export abstract class CascadeStore<ED extends EntityDict & BaseEntityDict> exten
data: projection2[attr],
filter: {
id: {
$in: ids
$in: difference(ids, subRows.map(ele => ele.id!))
},
},
}
@ -1432,7 +1432,7 @@ export abstract class CascadeStore<ED extends EntityDict & BaseEntityDict> exten
data,
operatorId,
targetEntity: entity as string,
bornAt: bornAt || now,
bornAt,
operEntity$oper: data instanceof Array ? {
id: 'dummy',
action: 'create',
@ -1600,7 +1600,7 @@ export abstract class CascadeStore<ED extends EntityDict & BaseEntityDict> exten
action,
data,
targetEntity: entity as string,
bornAt: bornAt || now,
bornAt,
operatorId,
operEntity$oper: {
id: 'dummy',
@ -1615,6 +1615,9 @@ export abstract class CascadeStore<ED extends EntityDict & BaseEntityDict> exten
)
)
},
filter: {
id: { $in: ids },
}
},
}
const closeRootMode = context.openRootMode();
@ -1756,7 +1759,7 @@ export abstract class CascadeStore<ED extends EntityDict & BaseEntityDict> exten
context: Cxt,
option: OP): OperationResult<ED> {
const { action, data, filter, id, bornAt } = operation;
const { action, data, filter } = operation;
let opData: any;
const wholeBeforeFns: Array<() => any> = [];
const wholeAfterFns: Array<() => any> = [];
@ -1820,7 +1823,7 @@ export abstract class CascadeStore<ED extends EntityDict & BaseEntityDict> exten
operation: ED[T]['Operation'],
context: Cxt,
option: OP): Promise<OperationResult<ED>> {
const { action, data, filter, id, bornAt } = operation;
const { action, data, filter, bornAt } = operation;
let opData: any;
const wholeBeforeFns: Array<() => Promise<OperationResult<ED>>> = [];
const wholeAfterFns: Array<() => Promise<OperationResult<ED>>> = [];

View File

@ -1,59 +1,13 @@
import { ActionDictOfEntityDict, BBWatcher, Checker, EntityDict, StorageSchema, Trigger, RowChecker, OakDataException, OakUniqueViolationException, UpdateTrigger, CHECKER_MAX_PRIORITY } from "../types";
import { ActionDictOfEntityDict, Checker, EntityDict, StorageSchema, RowChecker, OakUniqueViolationException, CHECKER_MAX_PRIORITY, AttrUpdateMatrix, LogicalChecker, OakAttrCantUpdateException } from "../types";
import { SyncContext } from "./SyncRowStore";
import { AsyncContext } from "./AsyncRowStore";
import { uniqBy, pick, intersection } from '../utils/lodash';
import { combineFilters } from "./filter";
import { createDynamicCheckers } from '../checkers';
import { createDynamicTriggers } from '../triggers';
import { pick, intersection, difference } from '../utils/lodash';
import { checkFilterContains, combineFilters } from "./filter";
import { EntityDict as BaseEntityDict } from '../base-app-domain/EntityDict';
import { triggers as ActionAuthTriggers } from './actionAuth';
import { createModiRelatedCheckers } from "./modi";
import { createCreateCheckers, createRemoveCheckers } from "./checker";
import { readOnlyActions } from "../actions/action";
export function getFullProjection<ED extends EntityDict & BaseEntityDict, T extends keyof ED>(entity: T, schema: StorageSchema<ED>) {
const { attributes } = schema[entity];
const projection: ED[T]['Selection']['data'] = {
id: 1,
$$createAt$$: 1,
$$updateAt$$: 1,
$$deleteAt$$: 1,
};
Object.keys(attributes).forEach(
(k) => Object.assign(projection, {
[k]: 1,
})
);
return projection;
}
function makeIntrinsicWatchers<ED extends EntityDict & BaseEntityDict>(schema: StorageSchema<ED>) {
const watchers: BBWatcher<ED, keyof ED>[] = [];
for (const entity in schema) {
const { attributes } = schema[entity];
const { expiresAt, expired } = attributes;
if (expiresAt && expiresAt.type === 'datetime' && expired && expired.type === 'boolean') {
// 如果有定义expiresAt和expired则自动生成一个检查的watcher
watchers.push({
entity,
name: `对象${entity}上的过期自动watcher`,
filter: () => {
return {
expired: false,
expiresAt: {
$lte: Date.now(),
},
};
},
action: 'update',
actionData: {
expired: true,
} as ED[keyof ED]['Update']['data'],
})
}
}
return watchers;
}
function checkUniqueBetweenRows(rows: Record<string, any>[], uniqAttrs: string[]) {
// 先检查这些行本身之间有无unique冲突
@ -101,7 +55,7 @@ function checkCountLessThan(count: number | Promise<number>, uniqAttrs: string[]
}
}
function checkUnique<ED extends EntityDict& BaseEntityDict, Cxt extends SyncContext<ED> | AsyncContext<ED>>(
function checkUnique<ED extends EntityDict & BaseEntityDict, Cxt extends SyncContext<ED> | AsyncContext<ED>>(
entity: keyof ED,
row: Record<string, any>,
context: Cxt,
@ -123,77 +77,8 @@ function checkUnique<ED extends EntityDict& BaseEntityDict, Cxt extends SyncCont
return checkCountLessThan(count, uniqAttrs, 0, row.id)
}
export function makeIntrinsicCTWs<ED extends EntityDict & BaseEntityDict, Cxt extends AsyncContext<ED>, FrontCxt extends SyncContext<ED>>(schema: StorageSchema<ED>, actionDefDict: ActionDictOfEntityDict<ED>) {
const checkers: Array<Checker<ED, keyof ED, Cxt | FrontCxt>> = createDynamicCheckers<ED, Cxt | FrontCxt>(schema);
const triggers: Array<Trigger<ED, keyof ED, Cxt>> = createDynamicTriggers<ED, Cxt>(schema);
// action状态转换矩阵相应的checker
for (const entity in actionDefDict) {
for (const attr in actionDefDict[entity]) {
const def = actionDefDict[entity]![attr];
const { stm, is } = def!;
for (const action in stm) {
const actionStm = stm[action]!;
const conditionalFilter = typeof actionStm[0] === 'string' ? {
[attr]: actionStm[0],
} : {
[attr]: {
$in: actionStm[0],
},
};
checkers.push({
action: action as any,
type: 'row',
entity,
filter: conditionalFilter,
errMsg: '',
} as RowChecker<ED, keyof ED, Cxt>);
// 这里用data类型的checker改数据了不太好先这样
checkers.push({
action: action as any,
type: 'data',
entity,
checker: (data) => {
Object.assign(data, {
[attr]: stm[action][1],
});
}
});
}
if (is) {
checkers.push({
action: 'create' as any,
type: 'data',
entity,
priority: 10, // 优先级要高先于真正的data检查进行
checker: (data) => {
if (data instanceof Array) {
data.forEach(
ele => {
if (!ele[attr]) {
Object.assign(ele, {
[attr]: is,
});
}
}
);
}
else {
if (!(data as ED[keyof ED]['CreateSingle']['data'])[attr]) {
Object.assign(data, {
[attr]: is,
});
}
}
}
});
}
}
}
// unique索引相应的checker
function createUniqueCheckers<ED extends EntityDict & BaseEntityDict, Cxt extends AsyncContext<ED>, FrontCxt extends SyncContext<ED>>(schema: StorageSchema<ED>) {
const checkers: Array<Checker<ED, keyof ED, Cxt | FrontCxt>> = [];
for (const entity in schema) {
const { indexes } = schema[entity];
if (indexes) {
@ -233,7 +118,7 @@ export function makeIntrinsicCTWs<ED extends EntityDict & BaseEntityDict, Cxt ex
const { data, filter: operationFilter } = operation as ED[keyof ED]['Update'];
if (data) {
const attrs = Object.keys(data);
const refAttrs = intersection(attrs, uniqAttrs);
if (refAttrs.length === 0) {
// 如果本次更新和unique约束的属性之间没有交集则直接返回
@ -248,7 +133,7 @@ export function makeIntrinsicCTWs<ED extends EntityDict & BaseEntityDict, Cxt ex
if (refAttrs.length === uniqAttrs.length) {
// 如果更新了全部属性,直接检查
const filter = pick(data, refAttrs);
// 在这些行以外的行不和更新后的键值冲突
const count = context.count(entity, {
filter: combineFilters(entity, context.getSchema(), [filter, {
@ -256,13 +141,13 @@ export function makeIntrinsicCTWs<ED extends EntityDict & BaseEntityDict, Cxt ex
}]),
}, { dontCollect: true });
const checkCount = checkCountLessThan(count, uniqAttrs, 0, operationFilter?.id);
// 更新的行只能有一行
const rowCount = context.count(entity, {
filter: operationFilter,
}, { dontCollect: true });
const checkRowCount = checkCountLessThan(rowCount, uniqAttrs, 1, operationFilter?.id);
// 如果更新的行数为零似乎也可以但这应该不可能出现吧by Xc 20230131
if (checkRowCount instanceof Promise) {
return Promise.all([checkCount, checkRowCount]).then(
@ -277,7 +162,7 @@ export function makeIntrinsicCTWs<ED extends EntityDict & BaseEntityDict, Cxt ex
[attr]: 1,
});
}
const checkWithRows = (rows2: ED[keyof ED]['Schema'][]) => {
const rows22 = rows2.map(
ele => Object.assign(ele, data)
@ -295,7 +180,7 @@ export function makeIntrinsicCTWs<ED extends EntityDict & BaseEntityDict, Cxt ex
);
}
};
const currentRows = context.select(entity, {
data: projection,
filter: operationFilter,
@ -313,11 +198,172 @@ export function makeIntrinsicCTWs<ED extends EntityDict & BaseEntityDict, Cxt ex
}
}
}
return checkers;
}
triggers.push(...(ActionAuthTriggers as Array<Trigger<ED, keyof ED, Cxt>>));
return {
triggers,
checkers,
watchers: makeIntrinsicWatchers(schema),
};
function createActionTransformerCheckers<ED extends EntityDict & BaseEntityDict, Cxt extends AsyncContext<ED>, FrontCxt extends SyncContext<ED>>(
actionDefDict: ActionDictOfEntityDict<ED>
) {
const checkers: Array<Checker<ED, keyof ED, Cxt | FrontCxt>> = [];
for (const entity in actionDefDict) {
for (const attr in actionDefDict[entity]) {
const def = actionDefDict[entity]![attr];
const { stm, is } = def!;
for (const action in stm) {
const actionStm = stm[action]!;
const conditionalFilter = typeof actionStm[0] === 'string' ? {
[attr]: actionStm[0],
} : {
[attr]: {
$in: actionStm[0],
},
};
checkers.push({
action: action as any,
type: 'row',
entity,
filter: conditionalFilter,
errMsg: '',
} as RowChecker<ED, keyof ED, Cxt>);
// 这里用data类型的checker改数据了不太好先这样
checkers.push({
action: action as any,
type: 'logicalData',
entity,
checker: (operation) => {
const { data } = operation;
if (data instanceof Array) {
data.forEach(
(d) => Object.assign(d, {
[attr]: stm[action][1],
})
);
}
else {
Object.assign(data, {
[attr]: stm[action][1],
});
}
}
});
}
if (is) {
checkers.push({
action: 'create' as ED[keyof ED]['Action'],
type: 'logicalData',
entity,
priority: 10, // 优先级要高先于真正的data检查进行
checker: (operation) => {
const { data } = operation;
if (data instanceof Array) {
(data as Readonly<ED[keyof ED]['CreateMulti']['data']>).forEach(
ele => {
if (!ele[attr]) {
Object.assign(ele, {
[attr]: is,
});
}
}
);
}
else {
if (!(data as Readonly<ED[keyof ED]['CreateSingle']['data']>)[attr]) {
Object.assign(data, {
[attr]: is,
});
}
}
}
});
}
}
}
return checkers;
}
function createAttrUpdateCheckers<ED extends EntityDict & BaseEntityDict, Cxt extends AsyncContext<ED>, FrontCxt extends SyncContext<ED>>(
schema: StorageSchema<ED>,
attrUpdateMatrix: AttrUpdateMatrix<ED>
) {
const checkers: Checker<ED, keyof ED, Cxt | FrontCxt>[] = [];
for (const entity in attrUpdateMatrix) {
const matrix = attrUpdateMatrix[entity]!;
const updateAttrs = Object.keys(matrix) as string[];
const { actions } = schema[entity];
const updateActions = actions.filter(
(a) => !readOnlyActions.concat(['create', 'remove']).includes(a)
);
/**
* entity定义了attrUpdateMatrixmatrix中的属性不允许更新
*/
const updateChecker: LogicalChecker<ED, keyof ED, Cxt | FrontCxt> = {
entity,
action: updateActions,
type: 'logicalData',
checker({ data, filter, action }, context) {
const attrs = Object.keys(data);
const extras = difference(attrs, updateAttrs);
if (extras.length > 0) {
throw new OakAttrCantUpdateException(entity, extras, '更新了不允许的属性');
}
const condition = attrs.map(ele => matrix[ele]!);
const actions = condition.map(ele => ele.actions).filter(ele => !!ele);
const filters = condition.map(ele => ele.filter).filter(ele => !!ele);
const a = actions.length > 0 && intersection(actions.flat());
const f = filters.length > 0 && combineFilters(entity, schema, filters);
if (a) {
if (!a.includes(action)) {
// 找到不满足的那个attr
const attrsIllegal = attrs.filter(
(attr) => matrix[attr]?.actions && !matrix[attr]?.actions?.includes(action!)
);
throw new OakAttrCantUpdateException(entity, attrsIllegal, `${attrsIllegal}不允许被${action}动作更新`);
}
}
if (f) {
const result = checkFilterContains<ED, keyof ED, Cxt>(entity, context as any, f, filter, true);
if (result instanceof Promise) {
return result.then(
(v) => {
if (!v) {
throw new OakAttrCantUpdateException(entity, attrs, '更新的行当前属性不满足约束,请仔细检查数据');
}
}
);
}
if (!result) {
throw new OakAttrCantUpdateException(entity, attrs, '更新的行当前属性不满足约束,请仔细检查数据');
}
}
}
};
checkers.push(updateChecker);
}
return checkers;
}
export function makeIntrinsicCheckers<ED extends EntityDict & BaseEntityDict, Cxt extends AsyncContext<ED>, FrontCxt extends SyncContext<ED>>(
schema: StorageSchema<ED>,
actionDefDict: ActionDictOfEntityDict<ED>,
attrUpdateMatrix?: AttrUpdateMatrix<ED>,
) {
const checkers: Checker<ED, keyof ED, Cxt | FrontCxt>[] = [];
checkers.push(...createModiRelatedCheckers<ED, Cxt>(schema));
checkers.push(...createRemoveCheckers<ED, Cxt | FrontCxt>(schema));
checkers.push(...createCreateCheckers<ED, Cxt | FrontCxt>(schema));
// action状态转换矩阵相应的checker
checkers.push(...createActionTransformerCheckers(actionDefDict));
// unique索引相应的checker
checkers.push(...createUniqueCheckers<ED, Cxt, FrontCxt>(schema));
if (attrUpdateMatrix) {
// attrUpdateMatrix相应的checker
checkers.push(...createAttrUpdateCheckers<ED, Cxt, FrontCxt>(schema, attrUpdateMatrix));
}
return checkers;
}

View File

@ -0,0 +1,56 @@
import { ActionDictOfEntityDict, BBWatcher, Checker, EntityDict, StorageSchema, Trigger, Watcher, AttrUpdateMatrix } from "../types";
import { SyncContext } from "./SyncRowStore";
import { AsyncContext } from "./AsyncRowStore";
import { EntityDict as BaseEntityDict } from '../base-app-domain/EntityDict';
import { triggers as ActionAuthTriggers } from './actionAuth';
import { createModiRelatedTriggers } from "./modi";
import { makeIntrinsicCheckers } from "./IntrinsicCheckers";
function createExpiredWatchers<ED extends EntityDict & BaseEntityDict>(schema: StorageSchema<ED>) {
const watchers: BBWatcher<ED, keyof ED>[] = [];
for (const entity in schema) {
const { attributes } = schema[entity];
const { expiresAt, expired } = attributes;
if (expiresAt && expiresAt.type === 'datetime' && expired && expired.type === 'boolean') {
// 如果有定义expiresAt和expired则自动生成一个检查的watcher
watchers.push({
entity,
name: `对象${entity}上的过期自动watcher`,
filter: () => {
return {
expired: false,
expiresAt: {
$lte: Date.now(),
},
};
},
action: 'update',
actionData: {
expired: true,
} as ED[keyof ED]['Update']['data'],
})
}
}
return watchers;
}
export function makeIntrinsicCTWs<ED extends EntityDict & BaseEntityDict, Cxt extends AsyncContext<ED>, FrontCxt extends SyncContext<ED>>(
schema: StorageSchema<ED>,
actionDefDict: ActionDictOfEntityDict<ED>,
attrUpdateMatrix?: AttrUpdateMatrix<ED>,
) {
const checkers: Checker<ED, keyof ED, Cxt | FrontCxt>[] = makeIntrinsicCheckers<ED, Cxt, FrontCxt>(schema, actionDefDict, attrUpdateMatrix);
const triggers: Array<Trigger<ED, keyof ED, Cxt>> = createModiRelatedTriggers<ED, Cxt>(schema);
triggers.push(...(ActionAuthTriggers as Array<Trigger<ED, keyof ED, Cxt>>));
const watchers: Array<Watcher<ED, keyof ED, Cxt>> = createExpiredWatchers<ED>(schema);
return {
triggers,
checkers,
watchers,
};
}

View File

@ -3,13 +3,13 @@ import { EntityDict } from "../base-app-domain";
import { OakUnloggedInException, OakUserInvisibleException, OakUserUnpermittedException, StorageSchema } from "../types";
import { EntityDict as BaseEntityDict, AuthDeduceRelationMap } from "../types/Entity";
import { AsyncContext } from "./AsyncRowStore";
import { checkFilterContains, combineFilters, getRelevantIds } from "./filter";
import { checkFilterContains, combineFilters, getRelevantIds, translateCreateDataToFilter } from "./filter";
import { judgeRelation } from "./relation";
import { SyncContext } from "./SyncRowStore";
import { readOnlyActions } from '../actions/action';
import { difference, intersection, set, uniq, cloneDeep, groupBy } from '../utils/lodash';
import { SYSTEM_RESERVE_ENTITIES } from "../compiler/entities";
import { destructDirectPath, destructRelationPath } from "../utils/relationPath";
import { destructDirectUserPath, destructRelationPath } from "../utils/relationPath";
type OperationTree<ED extends EntityDict & BaseEntityDict> = {
@ -569,21 +569,7 @@ export class RelationAuth<ED extends EntityDict & BaseEntityDict> {
const { data, filter } = operation;
assert(!(data instanceof Array));
if (data) {
const data2: ED[T2]['Selection']['filter'] = {};
for (const attr in data) {
const rel = judgeRelation(this.schema, entity, attr);
if (rel === 1) {
// 只需要记住id和各种外键属性不这样处理有些古怪的属性比如coordinate其作为createdata和作为filter并不同构
/* if ((['id', 'entity', 'entityId'].includes(attr) || this.schema[entity].attributes[attr as any]?.type === 'ref') && typeof data[attr] === 'string') {
data2[attr] = data[attr];
} */
// 假设不再成立userEntityGrant需要relationEntity这样的属性
if (!['geometry', 'geography', 'st_geometry', 'st_point'].includes(this.schema[entity].attributes[attr as any]?.type!)) {
data2[attr] = data[attr];
}
}
}
return data2;
return translateCreateDataToFilter(this.schema, entity, data);
}
return filter;
};
@ -1439,8 +1425,7 @@ export class RelationAuth<ED extends EntityDict & BaseEntityDict> {
/**
* entity进行actions操作权限的userRelation关系
* @param params
* @param context
* todo paths改成复数以后这里还未充分测试过
* @param context
*/
export async function getUserRelationsByActions<ED extends EntityDict & BaseEntityDict, T extends keyof ED, Cxt extends AsyncContext<ED>>(params: {
entity: T;
@ -1531,7 +1516,7 @@ export async function getUserRelationsByActions<ED extends EntityDict & BaseEnti
async ({ path }) => {
const { value, recursive } = path!;
assert(!recursive);
const { getData, projection } = destructDirectPath(context.getSchema(), entity, value!, recursive);
const { getData, projection } = destructDirectUserPath(context.getSchema(), entity, value!);
const rows = await context.select(entity, {
data: projection,

View File

@ -4,13 +4,14 @@ import { checkFilterRepel, combineFilters } from "../store/filter";
import { CreateOpResult, EntityDict, OperateOption, SelectOption, TriggerDataAttribute, TriggerUuidAttribute, UpdateAtAttribute, UpdateOpResult } from "../types/Entity";
import { EntityDict as BaseEntityDict } from '../base-app-domain';
import { Logger } from "../types/Logger";
import { Checker, CheckerType, LogicalChecker, RelationChecker } from '../types/Auth';
import { Checker, CheckerType, LogicalChecker, RowChecker } from '../types/Auth';
import { Trigger, CreateTriggerCrossTxn, CreateTrigger, CreateTriggerInTxn, SelectTriggerAfter, UpdateTrigger, TRIGGER_DEFAULT_PRIORITY, CHECKER_PRIORITY_MAP, CHECKER_MAX_PRIORITY, TRIGGER_MIN_PRIORITY, VolatileTrigger } from "../types/Trigger";
import { AsyncContext } from './AsyncRowStore';
import { SyncContext } from './SyncRowStore';
import { translateCheckerInAsyncContext } from './checker';
import { generateNewIdAsync } from '../utils/uuid';
import { readOnlyActions } from '../actions/action';
import { OakMakeSureByMySelfException, StorageSchema } from '../types';
/**
* update可能会传入多种不同的actionupdate trigger
@ -87,10 +88,10 @@ export class TriggerExecutor<ED extends EntityDict & BaseEntityDict, Cxt extends
this.onVolatileTrigger = onVolatileTrigger;
}
registerChecker<T extends keyof ED>(checker: Checker<ED, T, Cxt>): void {
const { entity, action, type, conditionalFilter, mt } = checker;
registerChecker<T extends keyof ED>(checker: Checker<ED, T, Cxt>, schema: StorageSchema<ED>): void {
const { entity, action, type, mt } = checker;
const triggerName = `${String(entity)}${action}权限检查-${this.counter++}`;
const { fn, when } = translateCheckerInAsyncContext(checker);
const { fn, when } = translateCheckerInAsyncContext(checker, schema);
const trigger = {
checkerType: type,
@ -101,7 +102,7 @@ export class TriggerExecutor<ED extends EntityDict & BaseEntityDict, Cxt extends
fn,
when,
mt,
filter: conditionalFilter,
filter: (checker as RowChecker<ED, T, Cxt>).conditionalFilter,
} as UpdateTrigger<ED, T, Cxt>;
this.registerTrigger(trigger);
}
@ -288,15 +289,20 @@ export class TriggerExecutor<ED extends EntityDict & BaseEntityDict, Cxt extends
if (operation.action === 'create') {
if (data instanceof Array) {
ids = data.map(ele => ele.id!);
cxtStr = data[0].$$triggerData$$.cxtStr;
cxtStr = data[0].$$triggerData$$?.cxtStr || await context.toString();
}
else {
ids = [data.id!];
cxtStr = data.$$triggerData$$.cxtStr;
cxtStr = data.$$triggerData$$?.cxtStr || await context.toString();
}
}
else {
cxtStr = (<ED[T]['Update']['data']>data).$$triggerData$$.cxtStr;
/**
* trigger是makeSure使cxtcheckpoint反复调用
* trigger是takeEasy使context应也无大问题
* cxt内容by Xc 20240319
*/
cxtStr = (<ED[T]['Update']['data']>data).$$triggerData$$?.cxtStr || await context.toString();
const record = opRecords.find(
ele => (ele as CreateOpResult<ED, keyof ED>).id === operation.id,
);
@ -412,26 +418,25 @@ export class TriggerExecutor<ED extends EntityDict & BaseEntityDict, Cxt extends
assert(trigger && trigger.when === 'commit');
assert(ids.length > 0);
const { fn } = trigger as VolatileTrigger<ED, T, Cxt>;
await fn({ ids }, context, option);
const callback = await fn({ ids }, context, option);
if (trigger.strict === 'makeSure') {
try {
await context.operate(entity, {
id: await generateNewIdAsync(),
action: 'update',
data: {
[TriggerDataAttribute]: null,
[TriggerUuidAttribute]: null,
},
filter: {
id: {
$in: ids,
}
await context.operate(entity, {
id: await generateNewIdAsync(),
action: 'update',
data: {
[TriggerDataAttribute]: null,
[TriggerUuidAttribute]: null,
},
filter: {
id: {
$in: ids,
}
}, { includedDeleted: true, blockTrigger: true });
}
catch (err) {
throw err;
}
}
}, { includedDeleted: true, blockTrigger: true });
}
if (typeof callback === 'function') {
await callback(context, option);
}
}
@ -599,7 +604,9 @@ export class TriggerExecutor<ED extends EntityDict & BaseEntityDict, Cxt extends
}
catch (err) {
await context.rollback();
this.logger.error(`执行checkpoint时出错对象是「${entity as string}」,异常是`, err);
if (!(err instanceof OakMakeSureByMySelfException)) {
this.logger.error(`执行checkpoint时出错对象是「${entity as string}」,异常是`, err);
}
}
}
return result;

View File

@ -1,20 +1,31 @@
import assert from 'assert';
import { checkFilterContains, combineFilters } from "../store/filter";
import { checkFilterContains, combineFilters, translateCreateDataToFilter } from "../store/filter";
import { OakAttrNotNullException, OakInputIllegalException, OakRowInconsistencyException, OakUserUnpermittedException } from '../types/Exception';
import {
AuthDefDict, CascadeRelationItem, Checker, CreateTriggerInTxn,
EntityDict, OperateOption, SelectOption, StorageSchema, Trigger, UpdateTriggerInTxn, RelationHierarchy, SelectOpResult, SyncOrAsync, CascadeRemoveDefDict, CHECKER_MAX_PRIORITY
} from "../types";
Checker, CreateTriggerInTxn, EntityDict, OperateOption, SelectOption, StorageSchema, Trigger,
UpdateTriggerInTxn, SelectOpResult, CHECKER_MAX_PRIORITY } from "../types";
import { EntityDict as BaseEntityDict } from '../base-app-domain';
import { AsyncContext } from "./AsyncRowStore";
import { getFullProjection } from './actionDef';
import { SyncContext } from './SyncRowStore';
import { firstLetterUpperCase } from '../utils/string';
import { union, uniq, difference } from '../utils/lodash';
import { judgeRelation } from './relation';
import { generateNewId } from '../utils/uuid';
import { union, difference } from '../utils/lodash';
import { excludeUpdateActions } from '../actions/action';
function getFullProjection<ED extends EntityDict & BaseEntityDict, T extends keyof ED>(entity: T, schema: StorageSchema<ED>) {
const { attributes } = schema[entity];
const projection: ED[T]['Selection']['data'] = {
id: 1,
$$createAt$$: 1,
$$updateAt$$: 1,
$$deleteAt$$: 1,
};
Object.keys(attributes).forEach(
(k) => Object.assign(projection, {
[k]: 1,
})
);
return projection;
}
/**
*
* @param checker checker
@ -25,7 +36,7 @@ export function translateCheckerInAsyncContext<
ED extends EntityDict & BaseEntityDict,
T extends keyof ED,
Cxt extends AsyncContext<ED>
>(checker: Checker<ED, T, Cxt>): {
>(checker: Checker<ED, T, Cxt>, schema: StorageSchema<ED>): {
fn: Trigger<ED, T, Cxt>['fn'];
when: 'before' | 'after';
} {
@ -36,7 +47,7 @@ export function translateCheckerInAsyncContext<
const { checker: checkerFn } = checker;
const fn = (async ({ operation }, context) => {
const { data } = operation;
await checkerFn(data, context);
await checkerFn(data as Readonly<ED[T]['Create']['data']>, context);
return 0;
}) as CreateTriggerInTxn<ED, keyof ED, Cxt>['fn'];
return {
@ -47,78 +58,62 @@ export function translateCheckerInAsyncContext<
case 'row': {
const { filter, errMsg, inconsistentRows } = checker;
const fn = (async ({ operation }, context, option) => {
const { filter: operationFilter, action } = operation;
const filter2 = typeof filter === 'function' ? await (filter as Function)(operation, context, option) : filter;
const { filter: operationFilter, data, action } = operation;
const filter2 = typeof filter === 'function' ? await filter(operation, context, option) : filter;
if (['select', 'count', 'stat'].includes(action)) {
operation.filter = combineFilters(entity, context.getSchema(), [operationFilter, filter2]);
return 0;
}
else {
if (await checkFilterContains<ED, keyof ED, Cxt>(entity, context, filter2, operationFilter || {}, true)) {
return 0;
}
if (inconsistentRows) {
const { entity: entity2, selection: selection2 } = inconsistentRows;
const rows2 = await context.select(entity2, selection2(operationFilter), {
dontCollect: true,
blockTrigger: true,
});
const e = new OakRowInconsistencyException<ED>(undefined, errMsg);
e.addData(entity2, rows2);
throw e;
}
else {
const rows2 = await context.select(entity, {
data: getFullProjection(entity, context.getSchema()),
filter: Object.assign({}, operationFilter, {
$not: filter2,
})
}, {
dontCollect: true,
blockTrigger: true,
});
const e = new OakRowInconsistencyException<ED>(undefined, errMsg);
e.addData(entity, rows2);
throw e;
}
}
}) as UpdateTriggerInTxn<ED, T, Cxt>['fn'];
return {
fn,
when,
};
}
case 'relation': {
const { relationFilter, errMsg } = checker;
const fn = (async ({ operation }, context, option) => {
if (context.isRoot()) {
return 0;
}
// assert(operation.action !== 'create', `${entity as string}上的create动作定义了relation类型的checker,请使用expressionRelation替代`);
// 对后台而言将生成的relationFilter加到filter之上(select可以在此加以权限的过滤)
const result = typeof relationFilter === 'function' ? await relationFilter(operation, context, option) : relationFilter;
if (result) {
const { filter, action } = operation;
const checkSingle = async (f: ED[T]['Update']['filter']) => {
if (await checkFilterContains<ED, keyof ED, Cxt>(entity, context, filter2, f, true)) {
return;
}
if (inconsistentRows) {
const { entity: entity2, selection: selection2 } = inconsistentRows;
const rows2 = await context.select(entity2, selection2(operationFilter), {
dontCollect: true,
blockTrigger: true,
});
const e = new OakRowInconsistencyException<ED>(undefined, errMsg);
e.addData(entity2, rows2);
throw e;
}
else {
const rows2 = await context.select(entity, {
data: getFullProjection(entity, context.getSchema()),
filter: Object.assign({}, operationFilter, {
$not: filter2,
})
}, {
dontCollect: true,
blockTrigger: true,
});
const e = new OakRowInconsistencyException<ED>(undefined, errMsg);
e.addData(entity, rows2);
throw e;
}
};
let operationFilter2 = operationFilter;
if (action === 'create') {
console.warn(`${entity as string}对象的create类型的checker中存在无法转换为表达式形式的情况请尽量使用authDef格式定义这类checker`);
return 0;
}
if (['select', 'count', 'stat'].includes(action)) {
operation.filter = combineFilters(entity, context.getSchema(), [filter, result]);
return 0;
}
assert(filter);
if (await checkFilterContains<ED, T, Cxt>(entity, context, result, filter, true)) {
// 后台进行创建检查时以传入的data为准
assert(data);
if (data instanceof Array) {
for (const d of <ED[T]['CreateMulti']['data']>data) {
await checkSingle(translateCreateDataToFilter(schema, entity, d))
}
}
else {
await checkSingle(translateCreateDataToFilter(schema, entity, <ED[T]['CreateSingle']['data']><unknown>data))
}
return;
}
const errMsg2 = typeof errMsg === 'function' ? errMsg(operation, context, option) : errMsg;
throw new OakUserUnpermittedException<ED, T>(entity, operation, errMsg2);
assert(operationFilter2, 'row类型的checker遇到了操作的filter未定义');
await checkSingle(operationFilter2);
return 0;
}
return 0;
}) as UpdateTriggerInTxn<ED, T, Cxt>['fn'];
return {
fn,
@ -126,13 +121,9 @@ export function translateCheckerInAsyncContext<
};
}
case 'logical':
case 'logicalRelation':
case 'logicalData': {
const { checker: checkerFn } = checker;
const fn = (async ({ operation }, context, option) => {
if (context.isRoot() && type === 'logicalRelation') {
return 0;
}
await checkerFn(operation, context, option);
return 0;
}) as UpdateTriggerInTxn<ED, T, Cxt>['fn'];
@ -151,7 +142,7 @@ export function translateCheckerInSyncContext<
ED extends EntityDict & BaseEntityDict,
T extends keyof ED,
Cxt extends SyncContext<ED>
>(checker: Checker<ED, T, Cxt>): {
>(checker: Checker<ED, T, Cxt>, schema: StorageSchema<ED>): {
fn: (operation: ED[T]['Operation'], context: Cxt, option: OperateOption | SelectOption) => void;
when: 'before' | 'after';
} {
@ -160,20 +151,29 @@ export function translateCheckerInSyncContext<
switch (type) {
case 'data': {
const { checker: checkerFn } = checker;
const fn = (operation: ED[T]['Operation'], context: Cxt) => checkerFn(operation.data, context);
const fn = (operation: ED[T]['Operation'], context: Cxt) => checkerFn(operation.data as Readonly<ED[T]['Create']['data']>, context);
return {
fn,
when,
}
}
case 'row': {
const { filter, errMsg } = checker;
const { filter, errMsg, entity } = checker;
const fn = (operation: ED[T]['Operation'], context: Cxt, option: OperateOption | SelectOption) => {
const { filter: operationFilter, action } = operation;
const filter2 = typeof filter === 'function' ? (filter as Function)(operation, context, option) : filter;
assert(operationFilter);
const { filter: operationFilter, data, action } = operation;
const filter2 = typeof filter === 'function' ? filter(operation, context, option) : filter;
let operationFilter2 = operationFilter;
if (action === 'create') {
if (data) {
// 前端的策略是有data用data无data用filter
// 目前前端应该不可能制造出来createMultiple
assert(!(data instanceof Array));
operationFilter2 = translateCreateDataToFilter(schema, entity, data as ED[T]['CreateSingle']['data']);
}
}
assert(!(filter2 instanceof Promise));
if (checkFilterContains<ED, T, Cxt>(entity, context, filter2, operationFilter, true)) {
assert(operationFilter2, '定义了row类型的checker但却进行了无filter操作')
if (checkFilterContains<ED, T, Cxt>(entity, context, filter2, operationFilter2, true)) {
return;
}
const e = new OakRowInconsistencyException(undefined, errMsg || 'row checker condition illegal');
@ -184,42 +184,10 @@ export function translateCheckerInSyncContext<
when,
};
}
case 'relation': {
const { relationFilter, errMsg } = checker;
const fn = (operation: ED[T]['Operation'], context: Cxt, option: OperateOption | SelectOption) => {
if (context.isRoot()) {
return;
}
const result = typeof relationFilter === 'function' ? relationFilter(operation, context, option) : relationFilter;
assert(!(result instanceof Promise));
if (result) {
const { filter, action } = operation;
if (action === 'create') {
console.warn(`${entity as string}对象的create类型的checker中存在无法转换为表达式形式的情况请尽量使用authDef格式定义这类checker`);
return;
}
assert(filter);
if (checkFilterContains<ED, T, Cxt>(entity, context, result as ED[T]['Selection']['filter'], filter, true)) {
return;
}
const errMsg2 = typeof errMsg === 'function' ? errMsg(operation, context, option) : errMsg;
throw new OakUserUnpermittedException<ED, T>(entity, operation, errMsg2);
}
};
return {
fn,
when,
};
}
case 'logical':
case 'logicalRelation':
case 'logicalData': {
const { checker: checkerFn } = checker;
const fn = (operation: ED[T]['Operation'], context: Cxt, option: OperateOption | SelectOption) => {
if (context.isRoot() && type === 'logicalRelation') {
return;
}
const fn = (operation: ED[T]['Operation'], context: Cxt, option: OperateOption | SelectOption) => {
checkerFn(operation, context, option);
};
return {
@ -517,12 +485,12 @@ export function createCreateCheckers<ED extends EntityDict & BaseEntityDict, Cxt
checkAttributeLegal(schema, entity, data2);
};
if (data instanceof Array) {
data.forEach(
(data as Readonly<ED[keyof ED]['CreateMulti']['data']>).forEach(
ele => checkData(ele)
);
}
else {
checkData(data as ED[keyof ED]['CreateSingle']['data']);
checkData(data as Readonly<ED[keyof ED]['CreateSingle']['data']>);
}
}
}, {

View File

@ -6,29 +6,23 @@ import { AsyncContext } from './AsyncRowStore';
import { judgeRelation } from './relation';
import { SyncContext } from './SyncRowStore';
/* function getFilterAttributes(filter: Record<string, any>) {
const attributes = [] as string[];
for (const attr in filter) {
if (attr.startsWith('$') || attr.startsWith('#')) {
if (['$and', '$or'].includes(attr)) {
for (const f of filter[attr]) {
const a = getFilterAttributes(f);
attributes.push(...a);
}
export function translateCreateDataToFilter<ED extends EntityDict & BaseEntityDict, T extends keyof ED> (
schema: StorageSchema<ED>,
entity: T,
data: ED[T]['CreateSingle']['data'],
) {
const data2: ED[T]['Selection']['filter'] = {};
for (const attr in data) {
const rel = judgeRelation(schema, entity, attr);
if (rel === 1) {
// 只需要记住id和各种外键属性不这样处理有些古怪的属性比如coordinate其作为createdata和作为filter并不同构
if (!['geometry', 'geography', 'st_geometry', 'st_point'].includes(schema[entity].attributes[attr as any]?.type!)) {
data2[attr] = data[attr];
}
else if (attr === '$not') {
const a = getFilterAttributes(filter[attr]);
attributes.push(...a);
}
}
else {
attributes.push(attr);
}
}
return uniq(attributes);
} */
return data2;
}
/**
* join的对象过多

View File

@ -1,29 +0,0 @@
import assert from 'assert';
import { EntityDict as BaseEntityDict } from '../base-app-domain';
import { StorageSchema, EntityDict, Trigger, CreateTrigger } from '../types';
import { createModiRelatedTriggers } from '../store/modi';
import { AsyncContext } from '../store/AsyncRowStore';
import { SyncContext } from '../store/SyncRowStore';
/* function createOperTriggers<ED extends EntityDict & BaseEntityDict, Cxt extends AsyncContext<ED> | SyncContext<ED>>() {
return [
{
name: 'assign initial bornAt for local oper',
entity: 'oper',
action: 'create',
when: 'before',
fn({ operation }) {
const { data } = operation;
assert(!(data instanceof Array));
if (!data.bornAt) {
data.bornAt = Date.now();
}
return 1;
}
} as CreateTrigger<ED, 'oper', Cxt>
] as Trigger<ED, keyof ED, Cxt>[];
} */
export function createDynamicTriggers<ED extends EntityDict & BaseEntityDict, Cxt extends AsyncContext<ED> | SyncContext<ED>>(schema: StorageSchema<ED>) {
return createModiRelatedTriggers<ED, Cxt>(schema);
}

View File

@ -1,10 +1,10 @@
import { CascadeActionAuth, RelationHierarchy, CascadeRelationAuth, ActionOnRemove, SyncOrAsync } from ".";
import { CascadeActionAuth, CascadeRelationAuth, ActionOnRemove, SyncOrAsync } from ".";
import { AsyncContext } from "../store/AsyncRowStore";
import { SyncContext } from "../store/SyncRowStore";
import { EntityDict, OperateOption, SelectOption } from "../types/Entity";
import { ModiTurn } from './Trigger';
export type CheckerType = 'relation' | 'row' | 'data' | 'logical' | 'logicalRelation' | 'logicalData';
export type CheckerType = 'row' | 'data' | 'logical' | 'logicalData';
/**
* conditionalFilter是指该action发生时operation所操作的行中有满足conditionalFilter的行
@ -16,10 +16,7 @@ export type DataChecker<ED extends EntityDict, T extends keyof ED, Cxt extends A
entity: T;
mt?: ModiTurn;
action: Omit<ED[T]['Action'], 'remove'> | Array<Omit<ED[T]['Action'], 'remove'>>;
checker: (data: ED[T]['Create']['data'] | ED[T]['Update']['data'], context: Cxt) => SyncOrAsync<any>;
conditionalFilter?: ED[T]['Update']['filter'] | (
(operation: ED[T]['Operation'], context: Cxt, option: OperateOption) => SyncOrAsync<ED[T]['Selection']['filter']>
);
checker: (data: Readonly<ED[T]['Create']['data'] | ED[T]['Update']['data']>, context: Cxt) => SyncOrAsync<any>;
};
export type RowChecker<ED extends EntityDict, T extends keyof ED, Cxt extends AsyncContext<ED> | SyncContext<ED>> = {
@ -27,7 +24,7 @@ export type RowChecker<ED extends EntityDict, T extends keyof ED, Cxt extends As
type: 'row';
entity: T;
mt?: ModiTurn;
action: Omit<ED[T]['Action'], 'create'> | Array<Omit<ED[T]['Action'], 'create'>>;
action: ED[T]['Action'] | Array<ED[T]['Action']>; // create现在也允许写row约束其父对象上的状态
filter: ED[T]['Selection']['filter'] | (
(operation: ED[T]['Operation'] | ED[T]['Selection'], context: Cxt, option: OperateOption | SelectOption) => SyncOrAsync<ED[T]['Selection']['filter']>
); // 对行的额外检查条件
@ -41,24 +38,11 @@ export type RowChecker<ED extends EntityDict, T extends keyof ED, Cxt extends As
);
};
export type RelationChecker<ED extends EntityDict, T extends keyof ED, Cxt extends AsyncContext<ED> | SyncContext<ED>> = {
priority?: number;
type: 'relation';
entity: T;
mt?: ModiTurn;
when?: 'after';
action: ED[T]['Action'] | Array<ED[T]['Action']>;
relationFilter: (operation: ED[T]['Operation'] | ED[T]['Selection'], context: Cxt, option: OperateOption | SelectOption) => SyncOrAsync<ED[T]['Selection']['filter']>, // 生成一个额外的relation相关的filter加在原先的filter上
errMsg: string | ((operation: ED[T]['Operation'] | ED[T]['Selection'], context: Cxt, option?: OperateOption | SelectOption) => string);
conditionalFilter?: ED[T]['Update']['filter'] | (
(operation: ED[T]['Operation'], context: Cxt, option: OperateOption) => SyncOrAsync<ED[T]['Selection']['filter']>
);
};
export type LogicalChecker<ED extends EntityDict, T extends keyof ED, Cxt extends AsyncContext<ED> | SyncContext<ED>> = {
priority?: number;
type: 'logical' | 'logicalData' | 'logicalRelation';
when?: 'after';
type: 'logical' | 'logicalData';
// when?: 'after';
mt?: ModiTurn;
entity: T;
action: ED[T]['Action'] | Array<ED[T]['Action']>;
@ -72,7 +56,7 @@ export type LogicalChecker<ED extends EntityDict, T extends keyof ED, Cxt extend
export type Checker<ED extends EntityDict, T extends keyof ED, Cxt extends AsyncContext<ED> | SyncContext<ED>> =
DataChecker<ED, T, Cxt> | RowChecker<ED, T, Cxt> | RelationChecker<ED, T, Cxt> | LogicalChecker<ED, T, Cxt>;
DataChecker<ED, T, Cxt> | RowChecker<ED, T, Cxt> | LogicalChecker<ED, T, Cxt>;
export type AuthDef<ED extends EntityDict, T extends keyof ED> = {

View File

@ -1,6 +1,6 @@
import { LocaleDef } from './Locale';
import { Index } from './Storage';
import { EntityShape, Configuration } from './Entity';
import { EntityShape, Configuration, EntityDict } from './Entity';
export type EntityDesc<
Schema extends EntityShape,
@ -11,4 +11,15 @@ export type EntityDesc<
indexes?: Index<Schema>[];
configuration?: Configuration;
recursiveDepth?: number;
}
};
// 定义对象的更新约束,在什么状态下可以(通过什么动作)更新什么属性
export type AttrUpdateMatrix<ED extends EntityDict> = {
[T in keyof ED]?: {
[A in keyof ED[T]['Update']['data']]?: {
actions?: ED[T]['Action'][];
filter?: NonNullable<ED[T]['Selection']['filter']>;
};
};
};

View File

@ -52,6 +52,11 @@ export class OakException<ED extends EntityDict> extends Error {
}
}
// 这个异常表示模块自己处理跨事务一致性框架pass在分布式数据传递时会用到
export class OakMakeSureByMySelfException<ED extends EntityDict> extends OakException<ED> {
}
export class OakDataException<ED extends EntityDict> extends OakException<ED> {
// 表示由数据层发现的异常
}
@ -205,7 +210,16 @@ export class OakInputIllegalException<ED extends EntityDict> extends OakUserExce
*/
export class OakAttrNotNullException<ED extends EntityDict> extends OakInputIllegalException<ED> {
constructor(entity: keyof ED, attributes: string[], message?: string) {
super(entity, attributes, message || '属性不允许为空');
super(entity, attributes, message || `属性[${attributes.join(',')}]不允许为空`);
}
}
/**
* update时对应属性的露出
*/
export class OakAttrCantUpdateException<ED extends EntityDict> extends OakInputIllegalException<ED> {
constructor(entity: keyof ED, attributes: string[], message?: string) {
super(entity, attributes, message || `属性[${attributes.join(',')}]不允许更新`);
}
}
@ -371,86 +385,75 @@ export function makeException<ED extends EntityDict>(data: {
[A: string]: any;
}) {
const { name } = data;
let e: OakException<ED> | undefined = undefined;
switch (name) {
case 'OakException': {
const e = new OakException(data.message);
e.setOpRecords(data.opRecords);
return e;
e = new OakException(data.message);
break;
}
case 'OakUserException': {
const e = new OakUserException(data.message);
e.setOpRecords(data.opRecords);
return e;
break;
}
case 'OakRowInconsistencyException': {
const e = new OakRowInconsistencyException(data.data, data.message);
e.setOpRecords(data.opRecords);
return e;
break;
}
case 'OakInputIllegalException': {
const e = new OakInputIllegalException(data.entity, data.attributes, data.message);
e.setOpRecords(data.opRecords);
return e;
break;
}
case 'OakAttrCantUpdateException': {
const e = new OakAttrCantUpdateException(data.entity, data.attributes, data.message);
break;
}
case 'OakUserUnpermittedException': {
const e = new OakUserUnpermittedException(data.entity, data.operation, data.message);
e.setOpRecords(data.opRecords);
return e;
break;
}
case 'OakUserInvisibleException': {
const e = new OakUserInvisibleException(data.entity, data.operation, data.message);
e.setOpRecords(data.opRecords);
return e;
break;
}
case 'OakUnloggedInException': {
const e = new OakUnloggedInException(data.message);
e.setOpRecords(data.opRecords);
return e;
break;
}
case 'OakCongruentRowExists': {
const e = new OakCongruentRowExists(data.entity, data.data, data.message);
e.setOpRecords(data.opRecords);
return e;
break;
}
case 'OakRowLockedException': {
const e = new OakRowLockedException(data.message);
e.setOpRecords(data.opRecords);
return e;
break;
}
case 'OakRowUnexistedException': {
const e = new OakRowUnexistedException(data.rows);
e.setOpRecords(data.opRecords);
return e;
break;
}
case 'OakDeadlock': {
const e = new OakDeadlock(data.message);
e.setOpRecords(data.opRecords);
return e;
break;
}
case 'OakDataException': {
const e = new OakDataException(data.message);
e.setOpRecords(data.opRecords);
return e;
break;
}
case 'OakNoRelationDefException': {
const e = new OakNoRelationDefException(data.entity, data.action, data.message);
e.setOpRecords(data.opRecords);
return e;
break;
}
case 'OakUniqueViolationException': {
const e = new OakUniqueViolationException(data.rows, data.message);
e.setOpRecords(data.opRecords);
return e;
break;
}
case 'OakImportDataParseException': {
const e = new OakImportDataParseException(data.message!, data.line, data.header);
e.setOpRecords(data.opRecords);
return e;
break;
}
case 'OakPreConditionUnsetException': {
const e = new OakPreConditionUnsetException(data.message, data.entity, data.code);
e.setOpRecords(data.opRecords);
return e;
break;
}
case 'OakAttrNotNullException': {
const e = new OakAttrNotNullException(
@ -458,22 +461,25 @@ export function makeException<ED extends EntityDict>(data: {
data.attributes,
data.message
);
e.setOpRecords(data.opRecords);
return e;
break;
}
case 'OakExternalException': {
const e = new OakExternalException(data.source, data.code, data.message, data.data);
return e;
break;
}
case 'OakNetworkException': {
const e = new OakNetworkException(data.message);
return e;
break;
}
case 'OakServerProxyException': {
const e = new OakServerProxyException(data.message);
return e;
break;
}
default:
return;
}
if (e) {
e.setOpRecords(data.opRecords);
return e;
}
}

View File

@ -37,7 +37,8 @@ export interface PullEntityDef<ED extends EntityDict & BaseEntityDict, T extends
export interface PushEntityDef<ED extends EntityDict & BaseEntityDict, T extends keyof ED, Cxt extends AsyncContext<ED>> {
direction: 'push';
entity: T; // 需要同步的entity
path: string; // 此entity到需要同步到的根entity的路径如果根entity和remote user之间不是relation关系其最后指向user的路径在pathToUser中指定
pathToRemoteEntity: string; // 此entity到需要同步到的根entity的路径如果根entity和remote user之间不是relation关系其最后指向user的路径在pathToUser中指定
pathToSelfEntity: string; // 此entity到selfEntity之间的路径
recursive?: boolean; // 表明path的最后一项是递归的(暂时无用)
relationName?: string; // 要同步的user与根对象的relation名称为空说明是userId)
actions?: ED[T]['Action'][];
@ -79,7 +80,7 @@ export interface SyncSelfConfigBase<ED extends EntityDict & BaseEntityDict> {
};
interface SyncSelfConfig<ED extends EntityDict & BaseEntityDict, Cxt extends AsyncContext<ED>> extends SyncSelfConfigBase<ED>{
getSelfEncryptInfo: (context: Cxt) => Promise<SelfEncryptInfo>;
getSelfEncryptInfo: (context: Cxt, selfEntityId: string) => Promise<SelfEncryptInfo>;
};
export interface SyncConfig<ED extends EntityDict & BaseEntityDict, Cxt extends AsyncContext<ED>> {

View File

@ -18,15 +18,14 @@ export const TRIGGER_MAX_PRIORITY = 50;
export const CHECKER_MAX_PRIORITY = 99;
/**
* logical可能会更改row和data的值data和row不能修改相关的值priority小一点以确保安全
* logical可能会更改row和data的值data和row不能修改相关的值
* logicalData去改data中的值
*/
export const CHECKER_PRIORITY_MAP: Record<CheckerType, number> = {
logicalData: 31,
logical: 33,
row: 51,
data: 61,
logicalData: 61,
relation: 71,
logicalRelation: 71,
};
interface TriggerBase<ED extends EntityDict, T extends keyof ED> {
@ -51,7 +50,8 @@ interface TriggerCrossTxn<ED extends EntityDict, Cxt extends AsyncContext<ED> |
when: 'commit',
strict?: 'takeEasy' | 'makeSure';
cs?: true; // cluster sensative集群敏感的需要由对应的集群进程统一处理
fn: (event: { ids: string[] }, context: Cxt, option: OperateOption) => Promise<number> | number;
fn: (event: { ids: string[] }, context: Cxt, option: OperateOption) =>
Promise<((context: Cxt, option: OperateOption) => Promise<any>) | void>; // 跨事务的trigger可能紧接着下来就要触发另一个跨事务trigger这里只能用回调的方式进行
}
export interface CreateTriggerCrossTxn<ED extends EntityDict, T extends keyof ED, Cxt extends AsyncContext<ED> | SyncContext<ED>>

View File

@ -122,74 +122,119 @@ export function destructRelationPath<ED extends EntityDict & BaseEntityDict, T e
}
/**
* entity的相对pathuserId
* entity的相对pathuser对象
* @param schema
* @param entity
* @param path path的最后一项一定指向user'aa.bb.cc.dd.user'
* @returns
*/
export function destructDirectUserPath<ED extends EntityDict & BaseEntityDict, T extends keyof ED>(
schema: StorageSchema<ED>,
entity: T,
path: string): {
projection: ED[T]['Selection']['data'];
getData: (d: Partial<ED[T]['Schema']>) => {
entity: keyof ED,
entityId: string,
userId: string,
}[] | undefined;
} {
const paths = path.split('.');
const last = paths.pop();
const path2 = paths.join('.');
const { projection, getData } = destructDirectPath<ED, T>(schema, entity, path);
return {
projection,
getData: (d) => {
const userInfo = getData(d, path2);
return userInfo?.map(
({ entity, data }) => ({
entity,
entityId: data.id!,
userId: (data[`${last}Id`] || data.entityId) as string
})
);
}
}
}
/**
* entity的相对path
* @param schema
* @param entity
* @param path
* @param recursive
* @returns
*/
export function destructDirectPath<ED extends EntityDict & BaseEntityDict, T extends keyof ED>(
schema: StorageSchema<ED>,
entity: T,
path: string,
recursive?: boolean
path: string
): {
projection: ED[T]['Selection']['data'];
getData: (d: Partial<ED[T]['Schema']>) => {
entity: keyof ED,
entityId: string,
userId: string,
getData: (d: Partial<ED[keyof ED]['Schema']>, path2?: string) => {
entity: keyof ED;
data: Partial<ED[keyof ED]['Schema']>;
}[] | undefined;
} {
assert(!recursive, '直接对象上不可能有recursive');
assert(path, '直接对象的路径最终要指向user对象不可能为空');
const paths = path.split('.');
const makeIter = (e: keyof ED, idx: number): {
projection: ED[keyof ED]['Selection']['data'];
getData: (d: Partial<ED[keyof ED]['Schema']>) => {
entity: keyof ED,
entityId: string,
userId: string,
getData: (d: Partial<ED[keyof ED]['Schema']>, path2?: string) => {
entity: keyof ED;
data: Partial<ED[keyof ED]['Schema']>;
}[] | undefined;
} => {
const attr = paths[idx];
const rel = judgeRelation(schema, e, attr);
if (idx === paths.length - 1) {
if (rel === 2) {
assert(attr === 'user');
return {
projection: {
id: 1,
entity: 1,
entityId: 1,
},
getData: (d) => {
getData: (d, p) => {
if (d) {
if (!p) {
return [{
entity: e,
data: d,
}];
}
assert(p === attr);
return [{
entity: e as string,
entityId: d.id!,
userId: d.entityId!,
entity: attr,
data: {
id: d.entityId as string,
} as Partial<ED[keyof ED]['Schema']>,
}];
}
},
};
}
else {
assert(rel === 'user');
return {
projection: {
id: 1,
[`${attr}Id`]: 1,
},
getData: (d) => {
getData: (d, p) => {
if (d) {
if (!p) {
return [{
entity: e,
data: d,
}];
}
assert(p === attr);
return [{
entity: e as string,
entityId: d.id!,
userId: d[`${attr}Id`] as string,
entity: rel as keyof ED,
data: {
id: d[`${attr}Id`] as string,
} as Partial<ED[keyof ED]['Schema']>,
}]
}
},
@ -203,7 +248,19 @@ export function destructDirectPath<ED extends EntityDict & BaseEntityDict, T ext
id: 1,
[attr]: projection,
},
getData: (d) => d[attr] && getData(d[attr]!),
getData: (d, p) => {
if (d) {
if (!p) {
return [{
entity: e,
data: d,
}];
}
const ps = p.split('.');
assert(ps[0] === attr);
return d[attr] && getData(d[attr]!, ps.slice(1).join('.'));
}
},
};
}
else if (typeof rel === 'string') {
@ -213,7 +270,19 @@ export function destructDirectPath<ED extends EntityDict & BaseEntityDict, T ext
id: 1,
[attr]: projection,
},
getData: (d) => d[attr] && getData(d[attr]!),
getData: (d, p) => {
if (d) {
if (!p) {
return [{
entity: e,
data: d,
}];
}
const ps = p.split('.');
assert(ps[0] === attr);
return d[attr] && getData(d[attr]!, ps.slice(1).join('.'));
}
},
};
}
else {
@ -228,11 +297,20 @@ export function destructDirectPath<ED extends EntityDict & BaseEntityDict, T ext
data: projection,
},
},
getData: (d) => d[attr] && (d[attr]! as Partial<ED[keyof ED]['Schema']>[]).map(ele => getData(ele)).flat().filter(ele => !!ele) as {
entity: keyof ED,
entityId: string,
userId: string,
}[],
getData: (d, p) => {
if (!p) {
return [{
entity: e,
data: d,
}];
}
const ps = p.split('.');
assert(ps[0] === attr);
return d[attr] && (d[attr]! as Partial<ED[keyof ED]['Schema']>[]).map(ele => getData(ele, ps.slice(1).join('.'))).flat().filter(ele => !!ele) as {
entity: keyof ED;
data: Partial<ED[keyof ED]['Schema']>;
}[];
}
}
}
};