mirror of
https://github.com/overleaf/overleaf.git
synced 2024-11-14 20:40:17 -05:00
merge multiple repositories into an existing monorepo
- merged using: 'monorepo_add.sh services-filestore:services/filestore' - see https://github.com/shopsys/monorepo-tools
This commit is contained in:
commit
e4d137eddf
54 changed files with 12143 additions and 0 deletions
10
services/filestore/.dockerignore
Normal file
10
services/filestore/.dockerignore
Normal file
|
@ -0,0 +1,10 @@
|
|||
node_modules/*
|
||||
gitrev
|
||||
.git
|
||||
.gitignore
|
||||
.npm
|
||||
.nvmrc
|
||||
nodemon.json
|
||||
uploads/
|
||||
user_files/
|
||||
template_files/
|
86
services/filestore/.eslintrc
Normal file
86
services/filestore/.eslintrc
Normal file
|
@ -0,0 +1,86 @@
|
|||
// this file was auto-generated, do not edit it directly.
|
||||
// instead run bin/update_build_scripts from
|
||||
// https://github.com/sharelatex/sharelatex-dev-environment
|
||||
{
|
||||
"extends": [
|
||||
"eslint:recommended",
|
||||
"standard",
|
||||
"prettier"
|
||||
],
|
||||
"parserOptions": {
|
||||
"ecmaVersion": 2018
|
||||
},
|
||||
"plugins": [
|
||||
"mocha",
|
||||
"chai-expect",
|
||||
"chai-friendly"
|
||||
],
|
||||
"env": {
|
||||
"node": true,
|
||||
"mocha": true
|
||||
},
|
||||
"rules": {
|
||||
// TODO(das7pad): remove overrides after fixing all the violations manually (https://github.com/overleaf/issues/issues/3882#issuecomment-878999671)
|
||||
// START of temporary overrides
|
||||
"array-callback-return": "off",
|
||||
"no-dupe-else-if": "off",
|
||||
"no-var": "off",
|
||||
"no-empty": "off",
|
||||
"node/handle-callback-err": "off",
|
||||
"no-loss-of-precision": "off",
|
||||
"node/no-callback-literal": "off",
|
||||
"node/no-path-concat": "off",
|
||||
"prefer-regex-literals": "off",
|
||||
// END of temporary overrides
|
||||
|
||||
// Swap the no-unused-expressions rule with a more chai-friendly one
|
||||
"no-unused-expressions": 0,
|
||||
"chai-friendly/no-unused-expressions": "error",
|
||||
|
||||
// Do not allow importing of implicit dependencies.
|
||||
"import/no-extraneous-dependencies": "error"
|
||||
},
|
||||
"overrides": [
|
||||
{
|
||||
// Test specific rules
|
||||
"files": ["test/**/*.js"],
|
||||
"globals": {
|
||||
"expect": true
|
||||
},
|
||||
"rules": {
|
||||
// mocha-specific rules
|
||||
"mocha/handle-done-callback": "error",
|
||||
"mocha/no-exclusive-tests": "error",
|
||||
"mocha/no-global-tests": "error",
|
||||
"mocha/no-identical-title": "error",
|
||||
"mocha/no-nested-tests": "error",
|
||||
"mocha/no-pending-tests": "error",
|
||||
"mocha/no-skipped-tests": "error",
|
||||
"mocha/no-mocha-arrows": "error",
|
||||
|
||||
// chai-specific rules
|
||||
"chai-expect/missing-assertion": "error",
|
||||
"chai-expect/terminating-properties": "error",
|
||||
|
||||
// prefer-arrow-callback applies to all callbacks, not just ones in mocha tests.
|
||||
// we don't enforce this at the top-level - just in tests to manage `this` scope
|
||||
// based on mocha's context mechanism
|
||||
"mocha/prefer-arrow-callback": "error"
|
||||
}
|
||||
},
|
||||
{
|
||||
// Backend specific rules
|
||||
"files": ["app/**/*.js", "app.js", "index.js"],
|
||||
"rules": {
|
||||
// don't allow console.log in backend code
|
||||
"no-console": "error",
|
||||
|
||||
// Do not allow importing of implicit dependencies.
|
||||
"import/no-extraneous-dependencies": ["error", {
|
||||
// Do not allow importing of devDependencies.
|
||||
"devDependencies": false
|
||||
}]
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
38
services/filestore/.github/ISSUE_TEMPLATE.md
vendored
Normal file
38
services/filestore/.github/ISSUE_TEMPLATE.md
vendored
Normal file
|
@ -0,0 +1,38 @@
|
|||
<!-- BUG REPORT TEMPLATE -->
|
||||
|
||||
## Steps to Reproduce
|
||||
<!-- Describe the steps leading up to when / where you found the bug. -->
|
||||
<!-- Screenshots may be helpful here. -->
|
||||
|
||||
1.
|
||||
2.
|
||||
3.
|
||||
|
||||
## Expected Behaviour
|
||||
<!-- What should have happened when you completed the steps above? -->
|
||||
|
||||
## Observed Behaviour
|
||||
<!-- What actually happened when you completed the steps above? -->
|
||||
<!-- Screenshots may be helpful here. -->
|
||||
|
||||
## Context
|
||||
<!-- How has this issue affected you? What were you trying to accomplish? -->
|
||||
|
||||
## Technical Info
|
||||
<!-- Provide any technical details that may be applicable (or N/A if not applicable). -->
|
||||
|
||||
* URL:
|
||||
* Browser Name and version:
|
||||
* Operating System and version (desktop or mobile):
|
||||
* Signed in as:
|
||||
* Project and/or file:
|
||||
|
||||
## Analysis
|
||||
<!--- Optionally, document investigation of / suggest a fix for the bug, e.g. 'comes from this line / commit' -->
|
||||
|
||||
## Who Needs to Know?
|
||||
<!-- If you want to bring this to the attention of particular people, @-mention them below. -->
|
||||
<!-- If a user reported this bug and should be notified when it is fixed, provide the Front conversation link. -->
|
||||
|
||||
-
|
||||
-
|
48
services/filestore/.github/PULL_REQUEST_TEMPLATE.md
vendored
Normal file
48
services/filestore/.github/PULL_REQUEST_TEMPLATE.md
vendored
Normal file
|
@ -0,0 +1,48 @@
|
|||
|
||||
<!-- ** This is an Overleaf public repository ** -->
|
||||
|
||||
<!-- Please review https://github.com/overleaf/overleaf/blob/master/CONTRIBUTING.md for guidance on what is expected of a contribution. -->
|
||||
|
||||
### Description
|
||||
|
||||
|
||||
|
||||
#### Screenshots
|
||||
|
||||
|
||||
|
||||
#### Related Issues / PRs
|
||||
|
||||
|
||||
|
||||
### Review
|
||||
|
||||
|
||||
|
||||
#### Potential Impact
|
||||
|
||||
|
||||
|
||||
#### Manual Testing Performed
|
||||
|
||||
- [ ]
|
||||
- [ ]
|
||||
|
||||
#### Accessibility
|
||||
|
||||
|
||||
|
||||
### Deployment
|
||||
|
||||
|
||||
|
||||
#### Deployment Checklist
|
||||
|
||||
- [ ] Update documentation not included in the PR (if any)
|
||||
- [ ]
|
||||
|
||||
#### Metrics and Monitoring
|
||||
|
||||
|
||||
|
||||
#### Who Needs to Know?
|
23
services/filestore/.github/dependabot.yml
vendored
Normal file
23
services/filestore/.github/dependabot.yml
vendored
Normal file
|
@ -0,0 +1,23 @@
|
|||
version: 2
|
||||
updates:
|
||||
- package-ecosystem: "npm"
|
||||
directory: "/"
|
||||
schedule:
|
||||
interval: "daily"
|
||||
|
||||
pull-request-branch-name:
|
||||
# Separate sections of the branch name with a hyphen
|
||||
# Docker images use the branch name and do not support slashes in tags
|
||||
# https://github.com/overleaf/google-ops/issues/822
|
||||
# https://docs.github.com/en/github/administering-a-repository/configuration-options-for-dependency-updates#pull-request-branch-nameseparator
|
||||
separator: "-"
|
||||
|
||||
# Block informal upgrades -- security upgrades use a separate queue.
|
||||
# https://docs.github.com/en/github/administering-a-repository/configuration-options-for-dependency-updates#open-pull-requests-limit
|
||||
open-pull-requests-limit: 0
|
||||
|
||||
# currently assign team-magma to all dependabot PRs - this may change in
|
||||
# future if we reorganise teams
|
||||
labels:
|
||||
- "dependencies"
|
||||
- "type:maintenance"
|
54
services/filestore/.gitignore
vendored
Normal file
54
services/filestore/.gitignore
vendored
Normal file
|
@ -0,0 +1,54 @@
|
|||
compileFolder
|
||||
|
||||
Compiled source #
|
||||
###################
|
||||
*.com
|
||||
*.class
|
||||
*.dll
|
||||
*.exe
|
||||
*.o
|
||||
*.so
|
||||
|
||||
# Packages #
|
||||
############
|
||||
# it's better to unpack these files and commit the raw source
|
||||
# git has its own built in compression methods
|
||||
*.7z
|
||||
*.dmg
|
||||
*.gz
|
||||
*.iso
|
||||
*.jar
|
||||
*.rar
|
||||
*.tar
|
||||
*.zip
|
||||
|
||||
# Logs and databases #
|
||||
######################
|
||||
*.log
|
||||
*.sql
|
||||
*.sqlite
|
||||
|
||||
# OS generated files #
|
||||
######################
|
||||
.DS_Store?
|
||||
ehthumbs.db
|
||||
Icon?
|
||||
Thumbs.db
|
||||
|
||||
/node_modules/*
|
||||
data/*/*
|
||||
|
||||
**/*.map
|
||||
cookies.txt
|
||||
uploads/*
|
||||
|
||||
user_files/*
|
||||
template_files/*
|
||||
|
||||
**.swp
|
||||
|
||||
/log.json
|
||||
hash_folder
|
||||
|
||||
# managed by dev-environment$ bin/update_build_scripts
|
||||
.npmrc
|
1
services/filestore/.nvmrc
Normal file
1
services/filestore/.nvmrc
Normal file
|
@ -0,0 +1 @@
|
|||
12.22.3
|
1
services/filestore/.prettierignore
Normal file
1
services/filestore/.prettierignore
Normal file
|
@ -0,0 +1 @@
|
|||
node_modules
|
11
services/filestore/.prettierrc
Normal file
11
services/filestore/.prettierrc
Normal file
|
@ -0,0 +1,11 @@
|
|||
# This file was auto-generated, do not edit it directly.
|
||||
# Instead run bin/update_build_scripts from
|
||||
# https://github.com/sharelatex/sharelatex-dev-environment
|
||||
{
|
||||
"arrowParens": "avoid",
|
||||
"semi": false,
|
||||
"singleQuote": true,
|
||||
"trailingComma": "es5",
|
||||
"tabWidth": 2,
|
||||
"useTabs": false
|
||||
}
|
27
services/filestore/Dockerfile
Normal file
27
services/filestore/Dockerfile
Normal file
|
@ -0,0 +1,27 @@
|
|||
# This file was auto-generated, do not edit it directly.
|
||||
# Instead run bin/update_build_scripts from
|
||||
# https://github.com/sharelatex/sharelatex-dev-environment
|
||||
|
||||
FROM node:12.22.3 as base
|
||||
|
||||
WORKDIR /app
|
||||
COPY install_deps.sh /app
|
||||
RUN chmod 0755 ./install_deps.sh && ./install_deps.sh
|
||||
|
||||
FROM base as app
|
||||
|
||||
#wildcard as some files may not be in all repos
|
||||
COPY package*.json npm-shrink*.json /app/
|
||||
|
||||
RUN npm ci --quiet
|
||||
|
||||
COPY . /app
|
||||
|
||||
FROM base
|
||||
|
||||
COPY --from=app /app /app
|
||||
RUN mkdir -p uploads user_files template_files \
|
||||
&& chown node:node uploads user_files template_files
|
||||
USER node
|
||||
|
||||
CMD ["node", "--expose-gc", "app.js"]
|
662
services/filestore/LICENSE
Normal file
662
services/filestore/LICENSE
Normal file
|
@ -0,0 +1,662 @@
|
|||
|
||||
GNU AFFERO GENERAL PUBLIC LICENSE
|
||||
Version 3, 19 November 2007
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
Preamble
|
||||
|
||||
The GNU Affero General Public License is a free, copyleft license for
|
||||
software and other kinds of works, specifically designed to ensure
|
||||
cooperation with the community in the case of network server software.
|
||||
|
||||
The licenses for most software and other practical works are designed
|
||||
to take away your freedom to share and change the works. By contrast,
|
||||
our General Public Licenses are intended to guarantee your freedom to
|
||||
share and change all versions of a program--to make sure it remains free
|
||||
software for all its users.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not
|
||||
price. Our General Public Licenses are designed to make sure that you
|
||||
have the freedom to distribute copies of free software (and charge for
|
||||
them if you wish), that you receive source code or can get it if you
|
||||
want it, that you can change the software or use pieces of it in new
|
||||
free programs, and that you know you can do these things.
|
||||
|
||||
Developers that use our General Public Licenses protect your rights
|
||||
with two steps: (1) assert copyright on the software, and (2) offer
|
||||
you this License which gives you legal permission to copy, distribute
|
||||
and/or modify the software.
|
||||
|
||||
A secondary benefit of defending all users' freedom is that
|
||||
improvements made in alternate versions of the program, if they
|
||||
receive widespread use, become available for other developers to
|
||||
incorporate. Many developers of free software are heartened and
|
||||
encouraged by the resulting cooperation. However, in the case of
|
||||
software used on network servers, this result may fail to come about.
|
||||
The GNU General Public License permits making a modified version and
|
||||
letting the public access it on a server without ever releasing its
|
||||
source code to the public.
|
||||
|
||||
The GNU Affero General Public License is designed specifically to
|
||||
ensure that, in such cases, the modified source code becomes available
|
||||
to the community. It requires the operator of a network server to
|
||||
provide the source code of the modified version running there to the
|
||||
users of that server. Therefore, public use of a modified version, on
|
||||
a publicly accessible server, gives the public access to the source
|
||||
code of the modified version.
|
||||
|
||||
An older license, called the Affero General Public License and
|
||||
published by Affero, was designed to accomplish similar goals. This is
|
||||
a different license, not a version of the Affero GPL, but Affero has
|
||||
released a new version of the Affero GPL which permits relicensing under
|
||||
this license.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow.
|
||||
|
||||
TERMS AND CONDITIONS
|
||||
|
||||
0. Definitions.
|
||||
|
||||
"This License" refers to version 3 of the GNU Affero General Public License.
|
||||
|
||||
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||
works, such as semiconductor masks.
|
||||
|
||||
"The Program" refers to any copyrightable work licensed under this
|
||||
License. Each licensee is addressed as "you". "Licensees" and
|
||||
"recipients" may be individuals or organizations.
|
||||
|
||||
To "modify" a work means to copy from or adapt all or part of the work
|
||||
in a fashion requiring copyright permission, other than the making of an
|
||||
exact copy. The resulting work is called a "modified version" of the
|
||||
earlier work or a work "based on" the earlier work.
|
||||
|
||||
A "covered work" means either the unmodified Program or a work based
|
||||
on the Program.
|
||||
|
||||
To "propagate" a work means to do anything with it that, without
|
||||
permission, would make you directly or secondarily liable for
|
||||
infringement under applicable copyright law, except executing it on a
|
||||
computer or modifying a private copy. Propagation includes copying,
|
||||
distribution (with or without modification), making available to the
|
||||
public, and in some countries other activities as well.
|
||||
|
||||
To "convey" a work means any kind of propagation that enables other
|
||||
parties to make or receive copies. Mere interaction with a user through
|
||||
a computer network, with no transfer of a copy, is not conveying.
|
||||
|
||||
An interactive user interface displays "Appropriate Legal Notices"
|
||||
to the extent that it includes a convenient and prominently visible
|
||||
feature that (1) displays an appropriate copyright notice, and (2)
|
||||
tells the user that there is no warranty for the work (except to the
|
||||
extent that warranties are provided), that licensees may convey the
|
||||
work under this License, and how to view a copy of this License. If
|
||||
the interface presents a list of user commands or options, such as a
|
||||
menu, a prominent item in the list meets this criterion.
|
||||
|
||||
1. Source Code.
|
||||
|
||||
The "source code" for a work means the preferred form of the work
|
||||
for making modifications to it. "Object code" means any non-source
|
||||
form of a work.
|
||||
|
||||
A "Standard Interface" means an interface that either is an official
|
||||
standard defined by a recognized standards body, or, in the case of
|
||||
interfaces specified for a particular programming language, one that
|
||||
is widely used among developers working in that language.
|
||||
|
||||
The "System Libraries" of an executable work include anything, other
|
||||
than the work as a whole, that (a) is included in the normal form of
|
||||
packaging a Major Component, but which is not part of that Major
|
||||
Component, and (b) serves only to enable use of the work with that
|
||||
Major Component, or to implement a Standard Interface for which an
|
||||
implementation is available to the public in source code form. A
|
||||
"Major Component", in this context, means a major essential component
|
||||
(kernel, window system, and so on) of the specific operating system
|
||||
(if any) on which the executable work runs, or a compiler used to
|
||||
produce the work, or an object code interpreter used to run it.
|
||||
|
||||
The "Corresponding Source" for a work in object code form means all
|
||||
the source code needed to generate, install, and (for an executable
|
||||
work) run the object code and to modify the work, including scripts to
|
||||
control those activities. However, it does not include the work's
|
||||
System Libraries, or general-purpose tools or generally available free
|
||||
programs which are used unmodified in performing those activities but
|
||||
which are not part of the work. For example, Corresponding Source
|
||||
includes interface definition files associated with source files for
|
||||
the work, and the source code for shared libraries and dynamically
|
||||
linked subprograms that the work is specifically designed to require,
|
||||
such as by intimate data communication or control flow between those
|
||||
subprograms and other parts of the work.
|
||||
|
||||
The Corresponding Source need not include anything that users
|
||||
can regenerate automatically from other parts of the Corresponding
|
||||
Source.
|
||||
|
||||
The Corresponding Source for a work in source code form is that
|
||||
same work.
|
||||
|
||||
2. Basic Permissions.
|
||||
|
||||
All rights granted under this License are granted for the term of
|
||||
copyright on the Program, and are irrevocable provided the stated
|
||||
conditions are met. This License explicitly affirms your unlimited
|
||||
permission to run the unmodified Program. The output from running a
|
||||
covered work is covered by this License only if the output, given its
|
||||
content, constitutes a covered work. This License acknowledges your
|
||||
rights of fair use or other equivalent, as provided by copyright law.
|
||||
|
||||
You may make, run and propagate covered works that you do not
|
||||
convey, without conditions so long as your license otherwise remains
|
||||
in force. You may convey covered works to others for the sole purpose
|
||||
of having them make modifications exclusively for you, or provide you
|
||||
with facilities for running those works, provided that you comply with
|
||||
the terms of this License in conveying all material for which you do
|
||||
not control copyright. Those thus making or running the covered works
|
||||
for you must do so exclusively on your behalf, under your direction
|
||||
and control, on terms that prohibit them from making any copies of
|
||||
your copyrighted material outside their relationship with you.
|
||||
|
||||
Conveying under any other circumstances is permitted solely under
|
||||
the conditions stated below. Sublicensing is not allowed; section 10
|
||||
makes it unnecessary.
|
||||
|
||||
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||
|
||||
No covered work shall be deemed part of an effective technological
|
||||
measure under any applicable law fulfilling obligations under article
|
||||
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||
similar laws prohibiting or restricting circumvention of such
|
||||
measures.
|
||||
|
||||
When you convey a covered work, you waive any legal power to forbid
|
||||
circumvention of technological measures to the extent such circumvention
|
||||
is effected by exercising rights under this License with respect to
|
||||
the covered work, and you disclaim any intention to limit operation or
|
||||
modification of the work as a means of enforcing, against the work's
|
||||
users, your or third parties' legal rights to forbid circumvention of
|
||||
technological measures.
|
||||
|
||||
4. Conveying Verbatim Copies.
|
||||
|
||||
You may convey verbatim copies of the Program's source code as you
|
||||
receive it, in any medium, provided that you conspicuously and
|
||||
appropriately publish on each copy an appropriate copyright notice;
|
||||
keep intact all notices stating that this License and any
|
||||
non-permissive terms added in accord with section 7 apply to the code;
|
||||
keep intact all notices of the absence of any warranty; and give all
|
||||
recipients a copy of this License along with the Program.
|
||||
|
||||
You may charge any price or no price for each copy that you convey,
|
||||
and you may offer support or warranty protection for a fee.
|
||||
|
||||
5. Conveying Modified Source Versions.
|
||||
|
||||
You may convey a work based on the Program, or the modifications to
|
||||
produce it from the Program, in the form of source code under the
|
||||
terms of section 4, provided that you also meet all of these conditions:
|
||||
|
||||
a) The work must carry prominent notices stating that you modified
|
||||
it, and giving a relevant date.
|
||||
|
||||
b) The work must carry prominent notices stating that it is
|
||||
released under this License and any conditions added under section
|
||||
7. This requirement modifies the requirement in section 4 to
|
||||
"keep intact all notices".
|
||||
|
||||
c) You must license the entire work, as a whole, under this
|
||||
License to anyone who comes into possession of a copy. This
|
||||
License will therefore apply, along with any applicable section 7
|
||||
additional terms, to the whole of the work, and all its parts,
|
||||
regardless of how they are packaged. This License gives no
|
||||
permission to license the work in any other way, but it does not
|
||||
invalidate such permission if you have separately received it.
|
||||
|
||||
d) If the work has interactive user interfaces, each must display
|
||||
Appropriate Legal Notices; however, if the Program has interactive
|
||||
interfaces that do not display Appropriate Legal Notices, your
|
||||
work need not make them do so.
|
||||
|
||||
A compilation of a covered work with other separate and independent
|
||||
works, which are not by their nature extensions of the covered work,
|
||||
and which are not combined with it such as to form a larger program,
|
||||
in or on a volume of a storage or distribution medium, is called an
|
||||
"aggregate" if the compilation and its resulting copyright are not
|
||||
used to limit the access or legal rights of the compilation's users
|
||||
beyond what the individual works permit. Inclusion of a covered work
|
||||
in an aggregate does not cause this License to apply to the other
|
||||
parts of the aggregate.
|
||||
|
||||
6. Conveying Non-Source Forms.
|
||||
|
||||
You may convey a covered work in object code form under the terms
|
||||
of sections 4 and 5, provided that you also convey the
|
||||
machine-readable Corresponding Source under the terms of this License,
|
||||
in one of these ways:
|
||||
|
||||
a) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by the
|
||||
Corresponding Source fixed on a durable physical medium
|
||||
customarily used for software interchange.
|
||||
|
||||
b) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by a
|
||||
written offer, valid for at least three years and valid for as
|
||||
long as you offer spare parts or customer support for that product
|
||||
model, to give anyone who possesses the object code either (1) a
|
||||
copy of the Corresponding Source for all the software in the
|
||||
product that is covered by this License, on a durable physical
|
||||
medium customarily used for software interchange, for a price no
|
||||
more than your reasonable cost of physically performing this
|
||||
conveying of source, or (2) access to copy the
|
||||
Corresponding Source from a network server at no charge.
|
||||
|
||||
c) Convey individual copies of the object code with a copy of the
|
||||
written offer to provide the Corresponding Source. This
|
||||
alternative is allowed only occasionally and noncommercially, and
|
||||
only if you received the object code with such an offer, in accord
|
||||
with subsection 6b.
|
||||
|
||||
d) Convey the object code by offering access from a designated
|
||||
place (gratis or for a charge), and offer equivalent access to the
|
||||
Corresponding Source in the same way through the same place at no
|
||||
further charge. You need not require recipients to copy the
|
||||
Corresponding Source along with the object code. If the place to
|
||||
copy the object code is a network server, the Corresponding Source
|
||||
may be on a different server (operated by you or a third party)
|
||||
that supports equivalent copying facilities, provided you maintain
|
||||
clear directions next to the object code saying where to find the
|
||||
Corresponding Source. Regardless of what server hosts the
|
||||
Corresponding Source, you remain obligated to ensure that it is
|
||||
available for as long as needed to satisfy these requirements.
|
||||
|
||||
e) Convey the object code using peer-to-peer transmission, provided
|
||||
you inform other peers where the object code and Corresponding
|
||||
Source of the work are being offered to the general public at no
|
||||
charge under subsection 6d.
|
||||
|
||||
A separable portion of the object code, whose source code is excluded
|
||||
from the Corresponding Source as a System Library, need not be
|
||||
included in conveying the object code work.
|
||||
|
||||
A "User Product" is either (1) a "consumer product", which means any
|
||||
tangible personal property which is normally used for personal, family,
|
||||
or household purposes, or (2) anything designed or sold for incorporation
|
||||
into a dwelling. In determining whether a product is a consumer product,
|
||||
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||
product received by a particular user, "normally used" refers to a
|
||||
typical or common use of that class of product, regardless of the status
|
||||
of the particular user or of the way in which the particular user
|
||||
actually uses, or expects or is expected to use, the product. A product
|
||||
is a consumer product regardless of whether the product has substantial
|
||||
commercial, industrial or non-consumer uses, unless such uses represent
|
||||
the only significant mode of use of the product.
|
||||
|
||||
"Installation Information" for a User Product means any methods,
|
||||
procedures, authorization keys, or other information required to install
|
||||
and execute modified versions of a covered work in that User Product from
|
||||
a modified version of its Corresponding Source. The information must
|
||||
suffice to ensure that the continued functioning of the modified object
|
||||
code is in no case prevented or interfered with solely because
|
||||
modification has been made.
|
||||
|
||||
If you convey an object code work under this section in, or with, or
|
||||
specifically for use in, a User Product, and the conveying occurs as
|
||||
part of a transaction in which the right of possession and use of the
|
||||
User Product is transferred to the recipient in perpetuity or for a
|
||||
fixed term (regardless of how the transaction is characterized), the
|
||||
Corresponding Source conveyed under this section must be accompanied
|
||||
by the Installation Information. But this requirement does not apply
|
||||
if neither you nor any third party retains the ability to install
|
||||
modified object code on the User Product (for example, the work has
|
||||
been installed in ROM).
|
||||
|
||||
The requirement to provide Installation Information does not include a
|
||||
requirement to continue to provide support service, warranty, or updates
|
||||
for a work that has been modified or installed by the recipient, or for
|
||||
the User Product in which it has been modified or installed. Access to a
|
||||
network may be denied when the modification itself materially and
|
||||
adversely affects the operation of the network or violates the rules and
|
||||
protocols for communication across the network.
|
||||
|
||||
Corresponding Source conveyed, and Installation Information provided,
|
||||
in accord with this section must be in a format that is publicly
|
||||
documented (and with an implementation available to the public in
|
||||
source code form), and must require no special password or key for
|
||||
unpacking, reading or copying.
|
||||
|
||||
7. Additional Terms.
|
||||
|
||||
"Additional permissions" are terms that supplement the terms of this
|
||||
License by making exceptions from one or more of its conditions.
|
||||
Additional permissions that are applicable to the entire Program shall
|
||||
be treated as though they were included in this License, to the extent
|
||||
that they are valid under applicable law. If additional permissions
|
||||
apply only to part of the Program, that part may be used separately
|
||||
under those permissions, but the entire Program remains governed by
|
||||
this License without regard to the additional permissions.
|
||||
|
||||
When you convey a copy of a covered work, you may at your option
|
||||
remove any additional permissions from that copy, or from any part of
|
||||
it. (Additional permissions may be written to require their own
|
||||
removal in certain cases when you modify the work.) You may place
|
||||
additional permissions on material, added by you to a covered work,
|
||||
for which you have or can give appropriate copyright permission.
|
||||
|
||||
Notwithstanding any other provision of this License, for material you
|
||||
add to a covered work, you may (if authorized by the copyright holders of
|
||||
that material) supplement the terms of this License with terms:
|
||||
|
||||
a) Disclaiming warranty or limiting liability differently from the
|
||||
terms of sections 15 and 16 of this License; or
|
||||
|
||||
b) Requiring preservation of specified reasonable legal notices or
|
||||
author attributions in that material or in the Appropriate Legal
|
||||
Notices displayed by works containing it; or
|
||||
|
||||
c) Prohibiting misrepresentation of the origin of that material, or
|
||||
requiring that modified versions of such material be marked in
|
||||
reasonable ways as different from the original version; or
|
||||
|
||||
d) Limiting the use for publicity purposes of names of licensors or
|
||||
authors of the material; or
|
||||
|
||||
e) Declining to grant rights under trademark law for use of some
|
||||
trade names, trademarks, or service marks; or
|
||||
|
||||
f) Requiring indemnification of licensors and authors of that
|
||||
material by anyone who conveys the material (or modified versions of
|
||||
it) with contractual assumptions of liability to the recipient, for
|
||||
any liability that these contractual assumptions directly impose on
|
||||
those licensors and authors.
|
||||
|
||||
All other non-permissive additional terms are considered "further
|
||||
restrictions" within the meaning of section 10. If the Program as you
|
||||
received it, or any part of it, contains a notice stating that it is
|
||||
governed by this License along with a term that is a further
|
||||
restriction, you may remove that term. If a license document contains
|
||||
a further restriction but permits relicensing or conveying under this
|
||||
License, you may add to a covered work material governed by the terms
|
||||
of that license document, provided that the further restriction does
|
||||
not survive such relicensing or conveying.
|
||||
|
||||
If you add terms to a covered work in accord with this section, you
|
||||
must place, in the relevant source files, a statement of the
|
||||
additional terms that apply to those files, or a notice indicating
|
||||
where to find the applicable terms.
|
||||
|
||||
Additional terms, permissive or non-permissive, may be stated in the
|
||||
form of a separately written license, or stated as exceptions;
|
||||
the above requirements apply either way.
|
||||
|
||||
8. Termination.
|
||||
|
||||
You may not propagate or modify a covered work except as expressly
|
||||
provided under this License. Any attempt otherwise to propagate or
|
||||
modify it is void, and will automatically terminate your rights under
|
||||
this License (including any patent licenses granted under the third
|
||||
paragraph of section 11).
|
||||
|
||||
However, if you cease all violation of this License, then your
|
||||
license from a particular copyright holder is reinstated (a)
|
||||
provisionally, unless and until the copyright holder explicitly and
|
||||
finally terminates your license, and (b) permanently, if the copyright
|
||||
holder fails to notify you of the violation by some reasonable means
|
||||
prior to 60 days after the cessation.
|
||||
|
||||
Moreover, your license from a particular copyright holder is
|
||||
reinstated permanently if the copyright holder notifies you of the
|
||||
violation by some reasonable means, this is the first time you have
|
||||
received notice of violation of this License (for any work) from that
|
||||
copyright holder, and you cure the violation prior to 30 days after
|
||||
your receipt of the notice.
|
||||
|
||||
Termination of your rights under this section does not terminate the
|
||||
licenses of parties who have received copies or rights from you under
|
||||
this License. If your rights have been terminated and not permanently
|
||||
reinstated, you do not qualify to receive new licenses for the same
|
||||
material under section 10.
|
||||
|
||||
9. Acceptance Not Required for Having Copies.
|
||||
|
||||
You are not required to accept this License in order to receive or
|
||||
run a copy of the Program. Ancillary propagation of a covered work
|
||||
occurring solely as a consequence of using peer-to-peer transmission
|
||||
to receive a copy likewise does not require acceptance. However,
|
||||
nothing other than this License grants you permission to propagate or
|
||||
modify any covered work. These actions infringe copyright if you do
|
||||
not accept this License. Therefore, by modifying or propagating a
|
||||
covered work, you indicate your acceptance of this License to do so.
|
||||
|
||||
10. Automatic Licensing of Downstream Recipients.
|
||||
|
||||
Each time you convey a covered work, the recipient automatically
|
||||
receives a license from the original licensors, to run, modify and
|
||||
propagate that work, subject to this License. You are not responsible
|
||||
for enforcing compliance by third parties with this License.
|
||||
|
||||
An "entity transaction" is a transaction transferring control of an
|
||||
organization, or substantially all assets of one, or subdividing an
|
||||
organization, or merging organizations. If propagation of a covered
|
||||
work results from an entity transaction, each party to that
|
||||
transaction who receives a copy of the work also receives whatever
|
||||
licenses to the work the party's predecessor in interest had or could
|
||||
give under the previous paragraph, plus a right to possession of the
|
||||
Corresponding Source of the work from the predecessor in interest, if
|
||||
the predecessor has it or can get it with reasonable efforts.
|
||||
|
||||
You may not impose any further restrictions on the exercise of the
|
||||
rights granted or affirmed under this License. For example, you may
|
||||
not impose a license fee, royalty, or other charge for exercise of
|
||||
rights granted under this License, and you may not initiate litigation
|
||||
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||
any patent claim is infringed by making, using, selling, offering for
|
||||
sale, or importing the Program or any portion of it.
|
||||
|
||||
11. Patents.
|
||||
|
||||
A "contributor" is a copyright holder who authorizes use under this
|
||||
License of the Program or a work on which the Program is based. The
|
||||
work thus licensed is called the contributor's "contributor version".
|
||||
|
||||
A contributor's "essential patent claims" are all patent claims
|
||||
owned or controlled by the contributor, whether already acquired or
|
||||
hereafter acquired, that would be infringed by some manner, permitted
|
||||
by this License, of making, using, or selling its contributor version,
|
||||
but do not include claims that would be infringed only as a
|
||||
consequence of further modification of the contributor version. For
|
||||
purposes of this definition, "control" includes the right to grant
|
||||
patent sublicenses in a manner consistent with the requirements of
|
||||
this License.
|
||||
|
||||
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||
patent license under the contributor's essential patent claims, to
|
||||
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||
propagate the contents of its contributor version.
|
||||
|
||||
In the following three paragraphs, a "patent license" is any express
|
||||
agreement or commitment, however denominated, not to enforce a patent
|
||||
(such as an express permission to practice a patent or covenant not to
|
||||
sue for patent infringement). To "grant" such a patent license to a
|
||||
party means to make such an agreement or commitment not to enforce a
|
||||
patent against the party.
|
||||
|
||||
If you convey a covered work, knowingly relying on a patent license,
|
||||
and the Corresponding Source of the work is not available for anyone
|
||||
to copy, free of charge and under the terms of this License, through a
|
||||
publicly available network server or other readily accessible means,
|
||||
then you must either (1) cause the Corresponding Source to be so
|
||||
available, or (2) arrange to deprive yourself of the benefit of the
|
||||
patent license for this particular work, or (3) arrange, in a manner
|
||||
consistent with the requirements of this License, to extend the patent
|
||||
license to downstream recipients. "Knowingly relying" means you have
|
||||
actual knowledge that, but for the patent license, your conveying the
|
||||
covered work in a country, or your recipient's use of the covered work
|
||||
in a country, would infringe one or more identifiable patents in that
|
||||
country that you have reason to believe are valid.
|
||||
|
||||
If, pursuant to or in connection with a single transaction or
|
||||
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||
covered work, and grant a patent license to some of the parties
|
||||
receiving the covered work authorizing them to use, propagate, modify
|
||||
or convey a specific copy of the covered work, then the patent license
|
||||
you grant is automatically extended to all recipients of the covered
|
||||
work and works based on it.
|
||||
|
||||
A patent license is "discriminatory" if it does not include within
|
||||
the scope of its coverage, prohibits the exercise of, or is
|
||||
conditioned on the non-exercise of one or more of the rights that are
|
||||
specifically granted under this License. You may not convey a covered
|
||||
work if you are a party to an arrangement with a third party that is
|
||||
in the business of distributing software, under which you make payment
|
||||
to the third party based on the extent of your activity of conveying
|
||||
the work, and under which the third party grants, to any of the
|
||||
parties who would receive the covered work from you, a discriminatory
|
||||
patent license (a) in connection with copies of the covered work
|
||||
conveyed by you (or copies made from those copies), or (b) primarily
|
||||
for and in connection with specific products or compilations that
|
||||
contain the covered work, unless you entered into that arrangement,
|
||||
or that patent license was granted, prior to 28 March 2007.
|
||||
|
||||
Nothing in this License shall be construed as excluding or limiting
|
||||
any implied license or other defenses to infringement that may
|
||||
otherwise be available to you under applicable patent law.
|
||||
|
||||
12. No Surrender of Others' Freedom.
|
||||
|
||||
If conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot convey a
|
||||
covered work so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you may
|
||||
not convey it at all. For example, if you agree to terms that obligate you
|
||||
to collect a royalty for further conveying from those to whom you convey
|
||||
the Program, the only way you could satisfy both those terms and this
|
||||
License would be to refrain entirely from conveying the Program.
|
||||
|
||||
13. Remote Network Interaction; Use with the GNU General Public License.
|
||||
|
||||
Notwithstanding any other provision of this License, if you modify the
|
||||
Program, your modified version must prominently offer all users
|
||||
interacting with it remotely through a computer network (if your version
|
||||
supports such interaction) an opportunity to receive the Corresponding
|
||||
Source of your version by providing access to the Corresponding Source
|
||||
from a network server at no charge, through some standard or customary
|
||||
means of facilitating copying of software. This Corresponding Source
|
||||
shall include the Corresponding Source for any work covered by version 3
|
||||
of the GNU General Public License that is incorporated pursuant to the
|
||||
following paragraph.
|
||||
|
||||
Notwithstanding any other provision of this License, you have
|
||||
permission to link or combine any covered work with a work licensed
|
||||
under version 3 of the GNU General Public License into a single
|
||||
combined work, and to convey the resulting work. The terms of this
|
||||
License will continue to apply to the part which is the covered work,
|
||||
but the work with which it is combined will remain governed by version
|
||||
3 of the GNU General Public License.
|
||||
|
||||
14. Revised Versions of this License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions of
|
||||
the GNU Affero General Public License from time to time. Such new versions
|
||||
will be similar in spirit to the present version, but may differ in detail to
|
||||
address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the
|
||||
Program specifies that a certain numbered version of the GNU Affero General
|
||||
Public License "or any later version" applies to it, you have the
|
||||
option of following the terms and conditions either of that numbered
|
||||
version or of any later version published by the Free Software
|
||||
Foundation. If the Program does not specify a version number of the
|
||||
GNU Affero General Public License, you may choose any version ever published
|
||||
by the Free Software Foundation.
|
||||
|
||||
If the Program specifies that a proxy can decide which future
|
||||
versions of the GNU Affero General Public License can be used, that proxy's
|
||||
public statement of acceptance of a version permanently authorizes you
|
||||
to choose that version for the Program.
|
||||
|
||||
Later license versions may give you additional or different
|
||||
permissions. However, no additional obligations are imposed on any
|
||||
author or copyright holder as a result of your choosing to follow a
|
||||
later version.
|
||||
|
||||
15. Disclaimer of Warranty.
|
||||
|
||||
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
|
||||
16. Limitation of Liability.
|
||||
|
||||
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||
SUCH DAMAGES.
|
||||
|
||||
17. Interpretation of Sections 15 and 16.
|
||||
|
||||
If the disclaimer of warranty and limitation of liability provided
|
||||
above cannot be given local legal effect according to their terms,
|
||||
reviewing courts shall apply local law that most closely approximates
|
||||
an absolute waiver of all civil liability in connection with the
|
||||
Program, unless a warranty or assumption of liability accompanies a
|
||||
copy of the Program in return for a fee.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
How to Apply These Terms to Your New Programs
|
||||
|
||||
If you develop a new program, and you want it to be of the greatest
|
||||
possible use to the public, the best way to achieve this is to make it
|
||||
free software which everyone can redistribute and change under these terms.
|
||||
|
||||
To do so, attach the following notices to the program. It is safest
|
||||
to attach them to the start of each source file to most effectively
|
||||
state the exclusion of warranty; and each file should have at least
|
||||
the "copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
<one line to give the program's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If your software can interact with users remotely through a computer
|
||||
network, you should also make sure that it provides a way for users to
|
||||
get its source. For example, if your program is a web application, its
|
||||
interface could display a "Source" link that leads users to an archive
|
||||
of the code. There are many ways you could offer source, and different
|
||||
solutions will be better for different programs; see section 13 for the
|
||||
specific requirements.
|
||||
|
||||
You should also get your employer (if you work as a programmer) or school,
|
||||
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||
For more information on this, and how to apply and follow the GNU AGPL, see
|
||||
<http://www.gnu.org/licenses/>.
|
90
services/filestore/Makefile
Normal file
90
services/filestore/Makefile
Normal file
|
@ -0,0 +1,90 @@
|
|||
# This file was auto-generated, do not edit it directly.
|
||||
# Instead run bin/update_build_scripts from
|
||||
# https://github.com/sharelatex/sharelatex-dev-environment
|
||||
|
||||
BUILD_NUMBER ?= local
|
||||
BRANCH_NAME ?= $(shell git rev-parse --abbrev-ref HEAD)
|
||||
PROJECT_NAME = filestore
|
||||
BUILD_DIR_NAME = $(shell pwd | xargs basename | tr -cd '[a-zA-Z0-9_.\-]')
|
||||
|
||||
DOCKER_COMPOSE_FLAGS ?= -f docker-compose.yml
|
||||
DOCKER_COMPOSE := BUILD_NUMBER=$(BUILD_NUMBER) \
|
||||
BRANCH_NAME=$(BRANCH_NAME) \
|
||||
PROJECT_NAME=$(PROJECT_NAME) \
|
||||
MOCHA_GREP=${MOCHA_GREP} \
|
||||
docker-compose ${DOCKER_COMPOSE_FLAGS}
|
||||
|
||||
DOCKER_COMPOSE_TEST_ACCEPTANCE = \
|
||||
COMPOSE_PROJECT_NAME=test_acceptance_$(BUILD_DIR_NAME) $(DOCKER_COMPOSE)
|
||||
|
||||
DOCKER_COMPOSE_TEST_UNIT = \
|
||||
COMPOSE_PROJECT_NAME=test_unit_$(BUILD_DIR_NAME) $(DOCKER_COMPOSE)
|
||||
|
||||
clean:
|
||||
-docker rmi ci/$(PROJECT_NAME):$(BRANCH_NAME)-$(BUILD_NUMBER)
|
||||
-docker rmi gcr.io/overleaf-ops/$(PROJECT_NAME):$(BRANCH_NAME)-$(BUILD_NUMBER)
|
||||
-$(DOCKER_COMPOSE_TEST_UNIT) down --rmi local
|
||||
-$(DOCKER_COMPOSE_TEST_ACCEPTANCE) down --rmi local
|
||||
|
||||
format:
|
||||
$(DOCKER_COMPOSE) run --rm test_unit npm run --silent format
|
||||
|
||||
format_fix:
|
||||
$(DOCKER_COMPOSE) run --rm test_unit npm run --silent format:fix
|
||||
|
||||
lint:
|
||||
$(DOCKER_COMPOSE) run --rm test_unit npm run --silent lint
|
||||
|
||||
test: format lint test_unit test_acceptance
|
||||
|
||||
test_unit:
|
||||
ifneq (,$(wildcard test/unit))
|
||||
$(DOCKER_COMPOSE_TEST_UNIT) run --rm test_unit
|
||||
$(MAKE) test_unit_clean
|
||||
endif
|
||||
|
||||
test_clean: test_unit_clean
|
||||
test_unit_clean:
|
||||
ifneq (,$(wildcard test/unit))
|
||||
$(DOCKER_COMPOSE_TEST_UNIT) down -v -t 0
|
||||
endif
|
||||
|
||||
test_acceptance: test_acceptance_clean test_acceptance_pre_run test_acceptance_run
|
||||
$(MAKE) test_acceptance_clean
|
||||
|
||||
test_acceptance_debug: test_acceptance_clean test_acceptance_pre_run test_acceptance_run_debug
|
||||
$(MAKE) test_acceptance_clean
|
||||
|
||||
test_acceptance_run:
|
||||
ifneq (,$(wildcard test/acceptance))
|
||||
$(DOCKER_COMPOSE_TEST_ACCEPTANCE) run --rm test_acceptance
|
||||
endif
|
||||
|
||||
test_acceptance_run_debug:
|
||||
ifneq (,$(wildcard test/acceptance))
|
||||
$(DOCKER_COMPOSE_TEST_ACCEPTANCE) run -p 127.0.0.9:19999:19999 --rm test_acceptance npm run test:acceptance -- --inspect=0.0.0.0:19999 --inspect-brk
|
||||
endif
|
||||
|
||||
test_clean: test_acceptance_clean
|
||||
test_acceptance_clean:
|
||||
$(DOCKER_COMPOSE_TEST_ACCEPTANCE) down -v -t 0
|
||||
|
||||
test_acceptance_pre_run:
|
||||
ifneq (,$(wildcard test/acceptance/js/scripts/pre-run))
|
||||
$(DOCKER_COMPOSE_TEST_ACCEPTANCE) run --rm test_acceptance test/acceptance/js/scripts/pre-run
|
||||
endif
|
||||
|
||||
build:
|
||||
docker build --pull --tag ci/$(PROJECT_NAME):$(BRANCH_NAME)-$(BUILD_NUMBER) \
|
||||
--tag gcr.io/overleaf-ops/$(PROJECT_NAME):$(BRANCH_NAME)-$(BUILD_NUMBER) \
|
||||
.
|
||||
|
||||
tar:
|
||||
$(DOCKER_COMPOSE) up tar
|
||||
|
||||
publish:
|
||||
|
||||
docker push $(DOCKER_REPO)/$(PROJECT_NAME):$(BRANCH_NAME)-$(BUILD_NUMBER)
|
||||
|
||||
|
||||
.PHONY: clean test test_unit test_acceptance test_clean build publish
|
22
services/filestore/README.md
Normal file
22
services/filestore/README.md
Normal file
|
@ -0,0 +1,22 @@
|
|||
overleaf/filestore
|
||||
====================
|
||||
|
||||
An API for CRUD operations on binary files stored in S3
|
||||
|
||||
filestore acts as a proxy between the CLSIs and (currently) Amazon S3 storage, presenting a RESTful HTTP interface to the CLSIs on port 3009 by default. Urls are mapped to node functions in https://github.com/overleaf/filestore/blob/master/app.coffee . URLs are of the form:
|
||||
|
||||
* `/project/:project_id/file/:file_id`
|
||||
* `/template/:template_id/v/:version/:format`
|
||||
* `/project/:project_id/public/:public_file_id`
|
||||
* `/project/:project_id/size`
|
||||
* `/bucket/:bucket/key/*`
|
||||
* `/shutdown`
|
||||
* `/status` - returns `filestore sharelatex up` or `server is being shut down` (HTTP 500)
|
||||
* `/health_check`
|
||||
|
||||
License
|
||||
-------
|
||||
|
||||
The code in this repository is released under the GNU AFFERO GENERAL PUBLIC LICENSE, version 3. A copy can be found in the `LICENSE` file.
|
||||
|
||||
Copyright (c) Overleaf, 2014-2019.
|
161
services/filestore/app.js
Normal file
161
services/filestore/app.js
Normal file
|
@ -0,0 +1,161 @@
|
|||
const Metrics = require('@overleaf/metrics')
|
||||
Metrics.initialize(process.env.METRICS_APP_NAME || 'filestore')
|
||||
|
||||
const logger = require('logger-sharelatex')
|
||||
logger.initialize(process.env.METRICS_APP_NAME || 'filestore')
|
||||
|
||||
const settings = require('@overleaf/settings')
|
||||
const express = require('express')
|
||||
const bodyParser = require('body-parser')
|
||||
|
||||
const fileController = require('./app/js/FileController')
|
||||
const keyBuilder = require('./app/js/KeyBuilder')
|
||||
const healthCheckController = require('./app/js/HealthCheckController')
|
||||
|
||||
const RequestLogger = require('./app/js/RequestLogger')
|
||||
|
||||
const app = express()
|
||||
|
||||
app.use(RequestLogger.middleware)
|
||||
|
||||
if (settings.sentry && settings.sentry.dsn) {
|
||||
logger.initializeErrorReporting(settings.sentry.dsn)
|
||||
}
|
||||
|
||||
Metrics.open_sockets.monitor(logger)
|
||||
Metrics.memory.monitor(logger)
|
||||
if (Metrics.event_loop) {
|
||||
Metrics.event_loop.monitor(logger)
|
||||
}
|
||||
|
||||
app.use(function (req, res, next) {
|
||||
Metrics.inc('http-request')
|
||||
next()
|
||||
})
|
||||
|
||||
Metrics.injectMetricsRoute(app)
|
||||
|
||||
app.head(
|
||||
'/project/:project_id/file/:file_id',
|
||||
keyBuilder.userFileKeyMiddleware,
|
||||
fileController.getFileHead
|
||||
)
|
||||
app.get(
|
||||
'/project/:project_id/file/:file_id',
|
||||
keyBuilder.userFileKeyMiddleware,
|
||||
fileController.getFile
|
||||
)
|
||||
app.post(
|
||||
'/project/:project_id/file/:file_id',
|
||||
keyBuilder.userFileKeyMiddleware,
|
||||
fileController.insertFile
|
||||
)
|
||||
app.put(
|
||||
'/project/:project_id/file/:file_id',
|
||||
keyBuilder.userFileKeyMiddleware,
|
||||
bodyParser.json(),
|
||||
fileController.copyFile
|
||||
)
|
||||
app.delete(
|
||||
'/project/:project_id/file/:file_id',
|
||||
keyBuilder.userFileKeyMiddleware,
|
||||
fileController.deleteFile
|
||||
)
|
||||
app.delete(
|
||||
'/project/:project_id',
|
||||
keyBuilder.userProjectKeyMiddleware,
|
||||
fileController.deleteProject
|
||||
)
|
||||
|
||||
app.head(
|
||||
'/template/:template_id/v/:version/:format',
|
||||
keyBuilder.templateFileKeyMiddleware,
|
||||
fileController.getFileHead
|
||||
)
|
||||
app.get(
|
||||
'/template/:template_id/v/:version/:format',
|
||||
keyBuilder.templateFileKeyMiddleware,
|
||||
fileController.getFile
|
||||
)
|
||||
app.get(
|
||||
'/template/:template_id/v/:version/:format/:sub_type',
|
||||
keyBuilder.templateFileKeyMiddleware,
|
||||
fileController.getFile
|
||||
)
|
||||
app.post(
|
||||
'/template/:template_id/v/:version/:format',
|
||||
keyBuilder.templateFileKeyMiddleware,
|
||||
fileController.insertFile
|
||||
)
|
||||
|
||||
app.head(
|
||||
'/project/:project_id/public/:public_file_id',
|
||||
keyBuilder.publicFileKeyMiddleware,
|
||||
fileController.getFileHead
|
||||
)
|
||||
app.get(
|
||||
'/project/:project_id/public/:public_file_id',
|
||||
keyBuilder.publicFileKeyMiddleware,
|
||||
fileController.getFile
|
||||
)
|
||||
app.post(
|
||||
'/project/:project_id/public/:public_file_id',
|
||||
keyBuilder.publicFileKeyMiddleware,
|
||||
fileController.insertFile
|
||||
)
|
||||
app.put(
|
||||
'/project/:project_id/public/:public_file_id',
|
||||
keyBuilder.publicFileKeyMiddleware,
|
||||
bodyParser.json(),
|
||||
fileController.copyFile
|
||||
)
|
||||
app.delete(
|
||||
'/project/:project_id/public/:public_file_id',
|
||||
keyBuilder.publicFileKeyMiddleware,
|
||||
fileController.deleteFile
|
||||
)
|
||||
|
||||
app.get(
|
||||
'/project/:project_id/size',
|
||||
keyBuilder.publicProjectKeyMiddleware,
|
||||
fileController.directorySize
|
||||
)
|
||||
|
||||
app.get(
|
||||
'/bucket/:bucket/key/*',
|
||||
keyBuilder.bucketFileKeyMiddleware,
|
||||
fileController.getFile
|
||||
)
|
||||
|
||||
app.get('/status', function (req, res) {
|
||||
res.send('filestore sharelatex up')
|
||||
})
|
||||
|
||||
app.get('/health_check', healthCheckController.check)
|
||||
|
||||
app.use(RequestLogger.errorHandler)
|
||||
|
||||
const port = settings.internal.filestore.port || 3009
|
||||
const host = '0.0.0.0'
|
||||
|
||||
if (!module.parent) {
|
||||
// Called directly
|
||||
app.listen(port, host, error => {
|
||||
if (error) {
|
||||
logger.error('Error starting Filestore', error)
|
||||
throw error
|
||||
}
|
||||
logger.info(`Filestore starting up, listening on ${host}:${port}`)
|
||||
})
|
||||
}
|
||||
|
||||
process
|
||||
.on('unhandledRejection', (reason, p) => {
|
||||
logger.err(reason, 'Unhandled Rejection at Promise', p)
|
||||
})
|
||||
.on('uncaughtException', err => {
|
||||
logger.err(err, 'Uncaught Exception thrown')
|
||||
process.exit(1)
|
||||
})
|
||||
|
||||
module.exports = app
|
30
services/filestore/app/js/Errors.js
Normal file
30
services/filestore/app/js/Errors.js
Normal file
|
@ -0,0 +1,30 @@
|
|||
const OError = require('@overleaf/o-error')
|
||||
const { Errors } = require('@overleaf/object-persistor')
|
||||
|
||||
class HealthCheckError extends OError {}
|
||||
class ConversionsDisabledError extends OError {}
|
||||
class ConversionError extends OError {}
|
||||
class TimeoutError extends OError {}
|
||||
class InvalidParametersError extends OError {}
|
||||
|
||||
class FailedCommandError extends OError {
|
||||
constructor(command, code, stdout, stderr) {
|
||||
super('command failed with error exit code', {
|
||||
command,
|
||||
code,
|
||||
})
|
||||
this.stdout = stdout
|
||||
this.stderr = stderr
|
||||
this.code = code
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
FailedCommandError,
|
||||
ConversionsDisabledError,
|
||||
ConversionError,
|
||||
HealthCheckError,
|
||||
TimeoutError,
|
||||
InvalidParametersError,
|
||||
...Errors,
|
||||
}
|
214
services/filestore/app/js/FileController.js
Normal file
214
services/filestore/app/js/FileController.js
Normal file
|
@ -0,0 +1,214 @@
|
|||
const PersistorManager = require('./PersistorManager')
|
||||
const FileHandler = require('./FileHandler')
|
||||
const metrics = require('@overleaf/metrics')
|
||||
const parseRange = require('range-parser')
|
||||
const Errors = require('./Errors')
|
||||
const { pipeline } = require('stream')
|
||||
|
||||
const maxSizeInBytes = 1024 * 1024 * 1024 // 1GB
|
||||
|
||||
module.exports = {
|
||||
getFile,
|
||||
getFileHead,
|
||||
insertFile,
|
||||
copyFile,
|
||||
deleteFile,
|
||||
deleteProject,
|
||||
directorySize,
|
||||
}
|
||||
|
||||
function getFile(req, res, next) {
|
||||
const { key, bucket } = req
|
||||
const { format, style } = req.query
|
||||
const options = {
|
||||
key,
|
||||
bucket,
|
||||
format,
|
||||
style,
|
||||
}
|
||||
|
||||
metrics.inc('getFile')
|
||||
req.requestLogger.setMessage('getting file')
|
||||
req.requestLogger.addFields({
|
||||
key,
|
||||
bucket,
|
||||
format,
|
||||
style,
|
||||
cacheWarm: req.query.cacheWarm,
|
||||
})
|
||||
|
||||
if (req.headers.range) {
|
||||
const range = _getRange(req.headers.range)
|
||||
if (range) {
|
||||
options.start = range.start
|
||||
options.end = range.end
|
||||
req.requestLogger.addFields({ range })
|
||||
}
|
||||
}
|
||||
|
||||
FileHandler.getRedirectUrl(bucket, key, options, function (err, redirectUrl) {
|
||||
if (err) {
|
||||
metrics.inc('file_redirect_error')
|
||||
}
|
||||
|
||||
if (redirectUrl) {
|
||||
metrics.inc('file_redirect')
|
||||
return res.redirect(redirectUrl)
|
||||
}
|
||||
|
||||
FileHandler.getFile(bucket, key, options, function (err, fileStream) {
|
||||
if (err) {
|
||||
if (err instanceof Errors.NotFoundError) {
|
||||
res.sendStatus(404)
|
||||
} else {
|
||||
next(err)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
if (req.query.cacheWarm) {
|
||||
return res.sendStatus(200).end()
|
||||
}
|
||||
|
||||
pipeline(fileStream, res, err => {
|
||||
if (err && err.code === 'ERR_STREAM_PREMATURE_CLOSE') {
|
||||
res.end()
|
||||
} else if (err) {
|
||||
next(
|
||||
new Errors.ReadError(
|
||||
'error transferring stream',
|
||||
{ bucket, key, format, style },
|
||||
err
|
||||
)
|
||||
)
|
||||
}
|
||||
})
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
function getFileHead(req, res, next) {
|
||||
const { key, bucket } = req
|
||||
|
||||
metrics.inc('getFileSize')
|
||||
req.requestLogger.setMessage('getting file size')
|
||||
req.requestLogger.addFields({ key, bucket })
|
||||
|
||||
FileHandler.getFileSize(bucket, key, function (err, fileSize) {
|
||||
if (err) {
|
||||
if (err instanceof Errors.NotFoundError) {
|
||||
res.sendStatus(404)
|
||||
} else {
|
||||
next(err)
|
||||
}
|
||||
return
|
||||
}
|
||||
res.set('Content-Length', fileSize)
|
||||
res.status(200).end()
|
||||
})
|
||||
}
|
||||
|
||||
function insertFile(req, res, next) {
|
||||
metrics.inc('insertFile')
|
||||
const { key, bucket } = req
|
||||
|
||||
req.requestLogger.setMessage('inserting file')
|
||||
req.requestLogger.addFields({ key, bucket })
|
||||
|
||||
FileHandler.insertFile(bucket, key, req, function (err) {
|
||||
if (err) {
|
||||
next(err)
|
||||
} else {
|
||||
res.sendStatus(200)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
function copyFile(req, res, next) {
|
||||
metrics.inc('copyFile')
|
||||
const { key, bucket } = req
|
||||
const oldProjectId = req.body.source.project_id
|
||||
const oldFileId = req.body.source.file_id
|
||||
|
||||
req.requestLogger.addFields({
|
||||
key,
|
||||
bucket,
|
||||
oldProject_id: oldProjectId,
|
||||
oldFile_id: oldFileId,
|
||||
})
|
||||
req.requestLogger.setMessage('copying file')
|
||||
|
||||
PersistorManager.copyObject(bucket, `${oldProjectId}/${oldFileId}`, key)
|
||||
.then(() => res.sendStatus(200))
|
||||
.catch(err => {
|
||||
if (err) {
|
||||
if (err instanceof Errors.NotFoundError) {
|
||||
res.sendStatus(404)
|
||||
} else {
|
||||
next(err)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
function deleteFile(req, res, next) {
|
||||
metrics.inc('deleteFile')
|
||||
const { key, bucket } = req
|
||||
|
||||
req.requestLogger.addFields({ key, bucket })
|
||||
req.requestLogger.setMessage('deleting file')
|
||||
|
||||
FileHandler.deleteFile(bucket, key, function (err) {
|
||||
if (err) {
|
||||
next(err)
|
||||
} else {
|
||||
res.sendStatus(204)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
function deleteProject(req, res, next) {
|
||||
metrics.inc('deleteProject')
|
||||
const { key, bucket } = req
|
||||
|
||||
req.requestLogger.setMessage('deleting project')
|
||||
req.requestLogger.addFields({ key, bucket })
|
||||
|
||||
FileHandler.deleteProject(bucket, key, function (err) {
|
||||
if (err) {
|
||||
if (err instanceof Errors.InvalidParametersError) {
|
||||
return res.sendStatus(400)
|
||||
}
|
||||
next(err)
|
||||
} else {
|
||||
res.sendStatus(204)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
function directorySize(req, res, next) {
|
||||
metrics.inc('projectSize')
|
||||
const { project_id: projectId, bucket } = req
|
||||
|
||||
req.requestLogger.setMessage('getting project size')
|
||||
req.requestLogger.addFields({ projectId, bucket })
|
||||
|
||||
FileHandler.getDirectorySize(bucket, projectId, function (err, size) {
|
||||
if (err) {
|
||||
return next(err)
|
||||
}
|
||||
|
||||
res.json({ 'total bytes': size })
|
||||
req.requestLogger.addFields({ size })
|
||||
})
|
||||
}
|
||||
|
||||
function _getRange(header) {
|
||||
const parsed = parseRange(maxSizeInBytes, header)
|
||||
if (parsed === -1 || parsed === -2 || parsed.type !== 'bytes') {
|
||||
return null
|
||||
} else {
|
||||
const range = parsed[0]
|
||||
return { start: range.start, end: range.end }
|
||||
}
|
||||
}
|
98
services/filestore/app/js/FileConverter.js
Normal file
98
services/filestore/app/js/FileConverter.js
Normal file
|
@ -0,0 +1,98 @@
|
|||
const metrics = require('@overleaf/metrics')
|
||||
const Settings = require('@overleaf/settings')
|
||||
const { callbackify } = require('util')
|
||||
|
||||
const safeExec = require('./SafeExec').promises
|
||||
const { ConversionError } = require('./Errors')
|
||||
|
||||
const APPROVED_FORMATS = ['png']
|
||||
const FOURTY_SECONDS = 40 * 1000
|
||||
const KILL_SIGNAL = 'SIGTERM'
|
||||
|
||||
module.exports = {
|
||||
convert: callbackify(convert),
|
||||
thumbnail: callbackify(thumbnail),
|
||||
preview: callbackify(preview),
|
||||
promises: {
|
||||
convert,
|
||||
thumbnail,
|
||||
preview,
|
||||
},
|
||||
}
|
||||
|
||||
async function convert(sourcePath, requestedFormat) {
|
||||
const width = '600x'
|
||||
return _convert(sourcePath, requestedFormat, [
|
||||
'convert',
|
||||
'-define',
|
||||
`pdf:fit-page=${width}`,
|
||||
'-flatten',
|
||||
'-density',
|
||||
'300',
|
||||
`${sourcePath}[0]`,
|
||||
])
|
||||
}
|
||||
|
||||
async function thumbnail(sourcePath) {
|
||||
const width = '260x'
|
||||
return convert(sourcePath, 'png', [
|
||||
'convert',
|
||||
'-flatten',
|
||||
'-background',
|
||||
'white',
|
||||
'-density',
|
||||
'300',
|
||||
'-define',
|
||||
`pdf:fit-page=${width}`,
|
||||
`${sourcePath}[0]`,
|
||||
'-resize',
|
||||
width,
|
||||
])
|
||||
}
|
||||
|
||||
async function preview(sourcePath) {
|
||||
const width = '548x'
|
||||
return convert(sourcePath, 'png', [
|
||||
'convert',
|
||||
'-flatten',
|
||||
'-background',
|
||||
'white',
|
||||
'-density',
|
||||
'300',
|
||||
'-define',
|
||||
`pdf:fit-page=${width}`,
|
||||
`${sourcePath}[0]`,
|
||||
'-resize',
|
||||
width,
|
||||
])
|
||||
}
|
||||
|
||||
async function _convert(sourcePath, requestedFormat, command) {
|
||||
if (!APPROVED_FORMATS.includes(requestedFormat)) {
|
||||
throw new ConversionError('invalid format requested', {
|
||||
format: requestedFormat,
|
||||
})
|
||||
}
|
||||
|
||||
const timer = new metrics.Timer('imageConvert')
|
||||
const destPath = `${sourcePath}.${requestedFormat}`
|
||||
|
||||
command.push(destPath)
|
||||
command = Settings.commands.convertCommandPrefix.concat(command)
|
||||
|
||||
try {
|
||||
await safeExec(command, {
|
||||
killSignal: KILL_SIGNAL,
|
||||
timeout: FOURTY_SECONDS,
|
||||
})
|
||||
} catch (err) {
|
||||
throw new ConversionError(
|
||||
'something went wrong converting file',
|
||||
{ stderr: err.stderr, sourcePath, requestedFormat, destPath },
|
||||
err
|
||||
)
|
||||
}
|
||||
|
||||
timer.done()
|
||||
return destPath
|
||||
}
|
195
services/filestore/app/js/FileHandler.js
Normal file
195
services/filestore/app/js/FileHandler.js
Normal file
|
@ -0,0 +1,195 @@
|
|||
const Settings = require('@overleaf/settings')
|
||||
const { callbackify } = require('util')
|
||||
const fs = require('fs')
|
||||
const PersistorManager = require('./PersistorManager')
|
||||
const LocalFileWriter = require('./LocalFileWriter')
|
||||
const FileConverter = require('./FileConverter')
|
||||
const KeyBuilder = require('./KeyBuilder')
|
||||
const ImageOptimiser = require('./ImageOptimiser')
|
||||
const { ConversionError, InvalidParametersError } = require('./Errors')
|
||||
|
||||
module.exports = {
|
||||
insertFile: callbackify(insertFile),
|
||||
deleteFile: callbackify(deleteFile),
|
||||
deleteProject: callbackify(deleteProject),
|
||||
getFile: callbackify(getFile),
|
||||
getRedirectUrl: callbackify(getRedirectUrl),
|
||||
getFileSize: callbackify(getFileSize),
|
||||
getDirectorySize: callbackify(getDirectorySize),
|
||||
promises: {
|
||||
getFile,
|
||||
getRedirectUrl,
|
||||
insertFile,
|
||||
deleteFile,
|
||||
deleteProject,
|
||||
getFileSize,
|
||||
getDirectorySize,
|
||||
},
|
||||
}
|
||||
|
||||
async function insertFile(bucket, key, stream) {
|
||||
const convertedKey = KeyBuilder.getConvertedFolderKey(key)
|
||||
if (!convertedKey.match(/^[0-9a-f]{24}\/([0-9a-f]{24}|v\/[0-9]+\/[a-z]+)/i)) {
|
||||
throw new InvalidParametersError('key does not match validation regex', {
|
||||
bucket,
|
||||
key,
|
||||
convertedKey,
|
||||
})
|
||||
}
|
||||
if (Settings.enableConversions) {
|
||||
await PersistorManager.deleteDirectory(bucket, convertedKey)
|
||||
}
|
||||
await PersistorManager.sendStream(bucket, key, stream)
|
||||
}
|
||||
|
||||
async function deleteFile(bucket, key) {
|
||||
const convertedKey = KeyBuilder.getConvertedFolderKey(key)
|
||||
if (!convertedKey.match(/^[0-9a-f]{24}\/([0-9a-f]{24}|v\/[0-9]+\/[a-z]+)/i)) {
|
||||
throw new InvalidParametersError('key does not match validation regex', {
|
||||
bucket,
|
||||
key,
|
||||
convertedKey,
|
||||
})
|
||||
}
|
||||
const jobs = [PersistorManager.deleteObject(bucket, key)]
|
||||
if (Settings.enableConversions) {
|
||||
jobs.push(PersistorManager.deleteDirectory(bucket, convertedKey))
|
||||
}
|
||||
await Promise.all(jobs)
|
||||
}
|
||||
|
||||
async function deleteProject(bucket, key) {
|
||||
if (!key.match(/^[0-9a-f]{24}\//i)) {
|
||||
throw new InvalidParametersError('key does not match validation regex', {
|
||||
bucket,
|
||||
key,
|
||||
})
|
||||
}
|
||||
await PersistorManager.deleteDirectory(bucket, key)
|
||||
}
|
||||
|
||||
async function getFile(bucket, key, opts) {
|
||||
opts = opts || {}
|
||||
if (!opts.format && !opts.style) {
|
||||
return PersistorManager.getObjectStream(bucket, key, opts)
|
||||
} else {
|
||||
return _getConvertedFile(bucket, key, opts)
|
||||
}
|
||||
}
|
||||
|
||||
async function getRedirectUrl(bucket, key, opts) {
|
||||
// if we're doing anything unusual with options, or the request isn't for
|
||||
// one of the default buckets, return null so that we proxy the file
|
||||
opts = opts || {}
|
||||
if (
|
||||
!opts.start &&
|
||||
!opts.end &&
|
||||
!opts.format &&
|
||||
!opts.style &&
|
||||
Object.values(Settings.filestore.stores).includes(bucket) &&
|
||||
Settings.filestore.allowRedirects
|
||||
) {
|
||||
return PersistorManager.getRedirectUrl(bucket, key)
|
||||
}
|
||||
|
||||
return null
|
||||
}
|
||||
|
||||
async function getFileSize(bucket, key) {
|
||||
return PersistorManager.getObjectSize(bucket, key)
|
||||
}
|
||||
|
||||
async function getDirectorySize(bucket, projectId) {
|
||||
return PersistorManager.directorySize(bucket, projectId)
|
||||
}
|
||||
|
||||
async function _getConvertedFile(bucket, key, opts) {
|
||||
const convertedKey = KeyBuilder.addCachingToKey(key, opts)
|
||||
const exists = await PersistorManager.checkIfObjectExists(
|
||||
bucket,
|
||||
convertedKey
|
||||
)
|
||||
if (exists) {
|
||||
return PersistorManager.getObjectStream(bucket, convertedKey, opts)
|
||||
} else {
|
||||
return _getConvertedFileAndCache(bucket, key, convertedKey, opts)
|
||||
}
|
||||
}
|
||||
|
||||
async function _getConvertedFileAndCache(bucket, key, convertedKey, opts) {
|
||||
let convertedFsPath
|
||||
try {
|
||||
convertedFsPath = await _convertFile(bucket, key, opts)
|
||||
await ImageOptimiser.promises.compressPng(convertedFsPath)
|
||||
await PersistorManager.sendFile(bucket, convertedKey, convertedFsPath)
|
||||
} catch (err) {
|
||||
LocalFileWriter.deleteFile(convertedFsPath, () => {})
|
||||
throw new ConversionError(
|
||||
'failed to convert file',
|
||||
{ opts, bucket, key, convertedKey },
|
||||
err
|
||||
)
|
||||
}
|
||||
// Send back the converted file from the local copy to avoid problems
|
||||
// with the file not being present in S3 yet. As described in the
|
||||
// documentation below, we have already made a 'HEAD' request in
|
||||
// checkIfFileExists so we only have "eventual consistency" if we try
|
||||
// to stream it from S3 here. This was a cause of many 403 errors.
|
||||
//
|
||||
// "Amazon S3 provides read-after-write consistency for PUTS of new
|
||||
// objects in your S3 bucket in all regions with one caveat. The
|
||||
// caveat is that if you make a HEAD or GET request to the key name
|
||||
// (to find if the object exists) before creating the object, Amazon
|
||||
// S3 provides eventual consistency for read-after-write.""
|
||||
// https://docs.aws.amazon.com/AmazonS3/latest/dev/Introduction.html#ConsistencyModel
|
||||
const readStream = fs.createReadStream(convertedFsPath)
|
||||
readStream.on('end', function () {
|
||||
LocalFileWriter.deleteFile(convertedFsPath, function () {})
|
||||
})
|
||||
return readStream
|
||||
}
|
||||
|
||||
async function _convertFile(bucket, originalKey, opts) {
|
||||
let originalFsPath
|
||||
try {
|
||||
originalFsPath = await _writeFileToDisk(bucket, originalKey, opts)
|
||||
} catch (err) {
|
||||
throw new ConversionError(
|
||||
'unable to write file to disk',
|
||||
{ bucket, originalKey, opts },
|
||||
err
|
||||
)
|
||||
}
|
||||
|
||||
let promise
|
||||
if (opts.format) {
|
||||
promise = FileConverter.promises.convert(originalFsPath, opts.format)
|
||||
} else if (opts.style === 'thumbnail') {
|
||||
promise = FileConverter.promises.thumbnail(originalFsPath)
|
||||
} else if (opts.style === 'preview') {
|
||||
promise = FileConverter.promises.preview(originalFsPath)
|
||||
} else {
|
||||
throw new ConversionError('invalid file conversion options', {
|
||||
bucket,
|
||||
originalKey,
|
||||
opts,
|
||||
})
|
||||
}
|
||||
let destPath
|
||||
try {
|
||||
destPath = await promise
|
||||
} catch (err) {
|
||||
throw new ConversionError(
|
||||
'error converting file',
|
||||
{ bucket, originalKey, opts },
|
||||
err
|
||||
)
|
||||
}
|
||||
LocalFileWriter.deleteFile(originalFsPath, function () {})
|
||||
return destPath
|
||||
}
|
||||
|
||||
async function _writeFileToDisk(bucket, key, opts) {
|
||||
const fileStream = await PersistorManager.getObjectStream(bucket, key, opts)
|
||||
return LocalFileWriter.promises.writeStream(fileStream, key)
|
||||
}
|
69
services/filestore/app/js/HealthCheckController.js
Normal file
69
services/filestore/app/js/HealthCheckController.js
Normal file
|
@ -0,0 +1,69 @@
|
|||
const fs = require('fs')
|
||||
const path = require('path')
|
||||
const Settings = require('@overleaf/settings')
|
||||
const streamBuffers = require('stream-buffers')
|
||||
const { promisify } = require('util')
|
||||
const Stream = require('stream')
|
||||
|
||||
const pipeline = promisify(Stream.pipeline)
|
||||
const fsCopy = promisify(fs.copyFile)
|
||||
const fsUnlink = promisify(fs.unlink)
|
||||
|
||||
const { HealthCheckError } = require('./Errors')
|
||||
const FileConverter = require('./FileConverter').promises
|
||||
const FileHandler = require('./FileHandler').promises
|
||||
|
||||
async function checkCanGetFiles() {
|
||||
if (!Settings.health_check) {
|
||||
return
|
||||
}
|
||||
|
||||
const projectId = Settings.health_check.project_id
|
||||
const fileId = Settings.health_check.file_id
|
||||
const key = `${projectId}/${fileId}`
|
||||
const bucket = Settings.filestore.stores.user_files
|
||||
|
||||
const buffer = new streamBuffers.WritableStreamBuffer({
|
||||
initialSize: 100,
|
||||
})
|
||||
|
||||
const sourceStream = await FileHandler.getFile(bucket, key, {})
|
||||
try {
|
||||
await pipeline(sourceStream, buffer)
|
||||
} catch (err) {
|
||||
throw new HealthCheckError('failed to get health-check file', {}, err)
|
||||
}
|
||||
|
||||
if (!buffer.size()) {
|
||||
throw new HealthCheckError('no bytes written to download stream')
|
||||
}
|
||||
}
|
||||
|
||||
async function checkFileConvert() {
|
||||
if (!Settings.enableConversions) {
|
||||
return
|
||||
}
|
||||
|
||||
const imgPath = path.join(Settings.path.uploadFolder, '/tiny.pdf')
|
||||
|
||||
let resultPath
|
||||
try {
|
||||
await fsCopy('./tiny.pdf', imgPath)
|
||||
resultPath = await FileConverter.thumbnail(imgPath)
|
||||
} finally {
|
||||
if (resultPath) {
|
||||
await fsUnlink(resultPath)
|
||||
}
|
||||
await fsUnlink(imgPath)
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
check(req, res, next) {
|
||||
Promise.all([checkCanGetFiles(), checkFileConvert()])
|
||||
.then(() => res.sendStatus(200))
|
||||
.catch(err => {
|
||||
next(err)
|
||||
})
|
||||
},
|
||||
}
|
34
services/filestore/app/js/ImageOptimiser.js
Normal file
34
services/filestore/app/js/ImageOptimiser.js
Normal file
|
@ -0,0 +1,34 @@
|
|||
const logger = require('logger-sharelatex')
|
||||
const metrics = require('@overleaf/metrics')
|
||||
const { callbackify } = require('util')
|
||||
const safeExec = require('./SafeExec').promises
|
||||
|
||||
module.exports = {
|
||||
compressPng: callbackify(compressPng),
|
||||
promises: {
|
||||
compressPng,
|
||||
},
|
||||
}
|
||||
|
||||
async function compressPng(localPath, callback) {
|
||||
const timer = new metrics.Timer('compressPng')
|
||||
const args = ['optipng', localPath]
|
||||
const opts = {
|
||||
timeout: 30 * 1000,
|
||||
killSignal: 'SIGKILL',
|
||||
}
|
||||
|
||||
try {
|
||||
await safeExec(args, opts)
|
||||
timer.done()
|
||||
} catch (err) {
|
||||
if (err.code === 'SIGKILL') {
|
||||
logger.warn(
|
||||
{ err, stderr: err.stderr, localPath },
|
||||
'optimiser timeout reached'
|
||||
)
|
||||
} else {
|
||||
throw err
|
||||
}
|
||||
}
|
||||
}
|
93
services/filestore/app/js/KeyBuilder.js
Normal file
93
services/filestore/app/js/KeyBuilder.js
Normal file
|
@ -0,0 +1,93 @@
|
|||
const settings = require('@overleaf/settings')
|
||||
|
||||
module.exports = {
|
||||
getConvertedFolderKey,
|
||||
addCachingToKey,
|
||||
userFileKeyMiddleware,
|
||||
userProjectKeyMiddleware,
|
||||
publicFileKeyMiddleware,
|
||||
publicProjectKeyMiddleware,
|
||||
bucketFileKeyMiddleware,
|
||||
templateFileKeyMiddleware,
|
||||
}
|
||||
|
||||
function getConvertedFolderKey(key) {
|
||||
return `${key}-converted-cache/`
|
||||
}
|
||||
|
||||
function addCachingToKey(key, opts) {
|
||||
key = this.getConvertedFolderKey(key)
|
||||
|
||||
if (opts.format && !opts.style) {
|
||||
key = `${key}format-${opts.format}`
|
||||
}
|
||||
if (opts.style && !opts.format) {
|
||||
key = `${key}style-${opts.style}`
|
||||
}
|
||||
if (opts.style && opts.format) {
|
||||
key = `${key}format-${opts.format}-style-${opts.style}`
|
||||
}
|
||||
|
||||
return key
|
||||
}
|
||||
|
||||
function userFileKeyMiddleware(req, res, next) {
|
||||
const { project_id: projectId, file_id: fileId } = req.params
|
||||
req.key = `${projectId}/${fileId}`
|
||||
req.bucket = settings.filestore.stores.user_files
|
||||
next()
|
||||
}
|
||||
|
||||
function userProjectKeyMiddleware(req, res, next) {
|
||||
const { project_id: projectId } = req.params
|
||||
req.key = `${projectId}/`
|
||||
req.bucket = settings.filestore.stores.user_files
|
||||
next()
|
||||
}
|
||||
|
||||
function publicFileKeyMiddleware(req, res, next) {
|
||||
if (settings.filestore.stores.public_files == null) {
|
||||
return res.status(501).send('public files not available')
|
||||
}
|
||||
|
||||
const { project_id: projectId, public_file_id: publicFileId } = req.params
|
||||
req.key = `${projectId}/${publicFileId}`
|
||||
req.bucket = settings.filestore.stores.public_files
|
||||
|
||||
next()
|
||||
}
|
||||
|
||||
function bucketFileKeyMiddleware(req, res, next) {
|
||||
req.bucket = req.params.bucket
|
||||
req.key = req.params[0]
|
||||
next()
|
||||
}
|
||||
|
||||
function templateFileKeyMiddleware(req, res, next) {
|
||||
const {
|
||||
template_id: templateId,
|
||||
format,
|
||||
version,
|
||||
sub_type: subType,
|
||||
} = req.params
|
||||
|
||||
req.key = `${templateId}/v/${version}/${format}`
|
||||
|
||||
if (subType) {
|
||||
req.key = `${req.key}/${subType}`
|
||||
}
|
||||
|
||||
req.bucket = settings.filestore.stores.template_files
|
||||
req.version = version
|
||||
|
||||
next()
|
||||
}
|
||||
|
||||
function publicProjectKeyMiddleware(req, res, next) {
|
||||
const { project_id: projectId } = req.params
|
||||
|
||||
req.project_id = projectId
|
||||
req.bucket = settings.filestore.stores.user_files
|
||||
|
||||
next()
|
||||
}
|
56
services/filestore/app/js/LocalFileWriter.js
Normal file
56
services/filestore/app/js/LocalFileWriter.js
Normal file
|
@ -0,0 +1,56 @@
|
|||
const fs = require('fs')
|
||||
const uuid = require('node-uuid')
|
||||
const path = require('path')
|
||||
const Stream = require('stream')
|
||||
const { callbackify, promisify } = require('util')
|
||||
const metrics = require('@overleaf/metrics')
|
||||
const Settings = require('@overleaf/settings')
|
||||
const { WriteError } = require('./Errors')
|
||||
|
||||
module.exports = {
|
||||
promises: {
|
||||
writeStream,
|
||||
deleteFile,
|
||||
},
|
||||
writeStream: callbackify(writeStream),
|
||||
deleteFile: callbackify(deleteFile),
|
||||
}
|
||||
|
||||
const pipeline = promisify(Stream.pipeline)
|
||||
|
||||
async function writeStream(stream, key) {
|
||||
const timer = new metrics.Timer('writingFile')
|
||||
const fsPath = _getPath(key)
|
||||
|
||||
const writeStream = fs.createWriteStream(fsPath)
|
||||
try {
|
||||
await pipeline(stream, writeStream)
|
||||
timer.done()
|
||||
return fsPath
|
||||
} catch (err) {
|
||||
await deleteFile(fsPath)
|
||||
|
||||
throw new WriteError('problem writing file locally', { fsPath }, err)
|
||||
}
|
||||
}
|
||||
|
||||
async function deleteFile(fsPath) {
|
||||
if (!fsPath) {
|
||||
return
|
||||
}
|
||||
try {
|
||||
await promisify(fs.unlink)(fsPath)
|
||||
} catch (err) {
|
||||
if (err.code !== 'ENOENT') {
|
||||
throw new WriteError('failed to delete file', { fsPath }, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function _getPath(key) {
|
||||
if (key == null) {
|
||||
key = uuid.v1()
|
||||
}
|
||||
key = key.replace(/\//g, '-')
|
||||
return path.join(Settings.path.uploadFolder, key)
|
||||
}
|
10
services/filestore/app/js/PersistorManager.js
Normal file
10
services/filestore/app/js/PersistorManager.js
Normal file
|
@ -0,0 +1,10 @@
|
|||
const settings = require('@overleaf/settings')
|
||||
|
||||
const persistorSettings = settings.filestore
|
||||
persistorSettings.Metrics = require('@overleaf/metrics')
|
||||
persistorSettings.paths = settings.path
|
||||
|
||||
const ObjectPersistor = require('@overleaf/object-persistor')
|
||||
const persistor = ObjectPersistor(persistorSettings)
|
||||
|
||||
module.exports = persistor
|
77
services/filestore/app/js/RequestLogger.js
Normal file
77
services/filestore/app/js/RequestLogger.js
Normal file
|
@ -0,0 +1,77 @@
|
|||
const logger = require('logger-sharelatex')
|
||||
const metrics = require('@overleaf/metrics')
|
||||
|
||||
class RequestLogger {
|
||||
constructor() {
|
||||
this._logInfo = {}
|
||||
this._logMessage = 'http request'
|
||||
}
|
||||
|
||||
addFields(fields) {
|
||||
Object.assign(this._logInfo, fields)
|
||||
}
|
||||
|
||||
setMessage(message) {
|
||||
this._logMessage = message
|
||||
}
|
||||
|
||||
static errorHandler(err, req, res, next) {
|
||||
req.requestLogger.addFields({ error: err })
|
||||
res.status(500).send(err.message)
|
||||
}
|
||||
|
||||
static middleware(req, res, next) {
|
||||
const startTime = new Date()
|
||||
req.requestLogger = new RequestLogger()
|
||||
|
||||
// override the 'end' method to log and record metrics
|
||||
const end = res.end
|
||||
res.end = function () {
|
||||
// apply the standard request 'end' method before logging and metrics
|
||||
end.apply(this, arguments)
|
||||
|
||||
const responseTime = new Date() - startTime
|
||||
|
||||
const routePath = req.route && req.route.path.toString()
|
||||
|
||||
if (routePath) {
|
||||
metrics.timing('http_request', responseTime, null, {
|
||||
method: req.method,
|
||||
status_code: res.statusCode,
|
||||
path: routePath.replace(/\//g, '_').replace(/:/g, '').slice(1),
|
||||
})
|
||||
}
|
||||
|
||||
const level = res.statusCode >= 500 ? 'err' : 'log'
|
||||
logger[level](
|
||||
{
|
||||
req: {
|
||||
url: req.originalUrl || req.url,
|
||||
route: routePath,
|
||||
method: req.method,
|
||||
referrer: req.headers.referer || req.headers.referrer,
|
||||
'remote-addr':
|
||||
req.ip ||
|
||||
(req.socket && req.socket.remoteAddress) ||
|
||||
(req.socket &&
|
||||
req.socket.socket &&
|
||||
req.socket.socket.remoteAddress),
|
||||
'user-agent': req.headers['user-agent'],
|
||||
'content-length': req.headers['content-length'],
|
||||
},
|
||||
res: {
|
||||
'content-length': res._headers['content-length'],
|
||||
statusCode: res.statusCode,
|
||||
'response-time': responseTime,
|
||||
},
|
||||
info: req.requestLogger._logInfo,
|
||||
},
|
||||
req.requestLogger._logMessage
|
||||
)
|
||||
}
|
||||
|
||||
next()
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = RequestLogger
|
85
services/filestore/app/js/SafeExec.js
Normal file
85
services/filestore/app/js/SafeExec.js
Normal file
|
@ -0,0 +1,85 @@
|
|||
const lodashOnce = require('lodash.once')
|
||||
const childProcess = require('child_process')
|
||||
const Settings = require('@overleaf/settings')
|
||||
const { ConversionsDisabledError, FailedCommandError } = require('./Errors')
|
||||
|
||||
// execute a command in the same way as 'exec' but with a timeout that
|
||||
// kills all child processes
|
||||
//
|
||||
// we spawn the command with 'detached:true' to make a new process
|
||||
// group, then we can kill everything in that process group.
|
||||
|
||||
module.exports = safeExec
|
||||
module.exports.promises = safeExecPromise
|
||||
|
||||
// options are {timeout: number-of-milliseconds, killSignal: signal-name}
|
||||
function safeExec(command, options, callback) {
|
||||
if (!Settings.enableConversions) {
|
||||
return callback(
|
||||
new ConversionsDisabledError('image conversions are disabled')
|
||||
)
|
||||
}
|
||||
|
||||
const [cmd, ...args] = command
|
||||
|
||||
const child = childProcess.spawn(cmd, args, { detached: true })
|
||||
let stdout = ''
|
||||
let stderr = ''
|
||||
|
||||
let killTimer
|
||||
|
||||
const cleanup = lodashOnce(function (err) {
|
||||
if (killTimer) {
|
||||
clearTimeout(killTimer)
|
||||
}
|
||||
callback(err, stdout, stderr)
|
||||
})
|
||||
|
||||
if (options.timeout) {
|
||||
killTimer = setTimeout(function () {
|
||||
try {
|
||||
// use negative process id to kill process group
|
||||
process.kill(-child.pid, options.killSignal || 'SIGTERM')
|
||||
} catch (error) {
|
||||
cleanup(
|
||||
new FailedCommandError('failed to kill process after timeout', {
|
||||
command,
|
||||
options,
|
||||
pid: child.pid,
|
||||
})
|
||||
)
|
||||
}
|
||||
}, options.timeout)
|
||||
}
|
||||
|
||||
child.on('close', function (code, signal) {
|
||||
if (code || signal) {
|
||||
return cleanup(
|
||||
new FailedCommandError(command, code || signal, stdout, stderr)
|
||||
)
|
||||
}
|
||||
|
||||
cleanup()
|
||||
})
|
||||
|
||||
child.on('error', err => {
|
||||
cleanup(err)
|
||||
})
|
||||
child.stdout.on('data', chunk => {
|
||||
stdout += chunk
|
||||
})
|
||||
child.stderr.on('data', chunk => {
|
||||
stderr += chunk
|
||||
})
|
||||
}
|
||||
|
||||
function safeExecPromise(command, options) {
|
||||
return new Promise((resolve, reject) => {
|
||||
safeExec(command, options, (err, stdout, stderr) => {
|
||||
if (err) {
|
||||
reject(err)
|
||||
}
|
||||
resolve({ stdout, stderr })
|
||||
})
|
||||
})
|
||||
}
|
9
services/filestore/buildscript.txt
Normal file
9
services/filestore/buildscript.txt
Normal file
|
@ -0,0 +1,9 @@
|
|||
filestore
|
||||
--data-dirs=uploads,user_files,template_files
|
||||
--dependencies=s3,gcs
|
||||
--docker-repos=gcr.io/overleaf-ops
|
||||
--env-add=ENABLE_CONVERSIONS="true",USE_PROM_METRICS="true",AWS_S3_USER_FILES_BUCKET_NAME=fake_user_files,AWS_S3_TEMPLATE_FILES_BUCKET_NAME=fake_template_files,AWS_S3_PUBLIC_FILES_BUCKET_NAME=fake_public_files,GCS_USER_FILES_BUCKET_NAME=fake_userfiles,GCS_TEMPLATE_FILES_BUCKET_NAME=fake_templatefiles,GCS_PUBLIC_FILES_BUCKET_NAME=fake_publicfiles
|
||||
--env-pass-through=
|
||||
--node-version=12.22.3
|
||||
--public-repo=True
|
||||
--script-version=3.11.0
|
132
services/filestore/config/settings.defaults.js
Normal file
132
services/filestore/config/settings.defaults.js
Normal file
|
@ -0,0 +1,132 @@
|
|||
const Path = require('path')
|
||||
|
||||
// environment variables renamed for consistency
|
||||
// use AWS_ACCESS_KEY_ID-style going forward
|
||||
if (process.env.AWS_KEY && !process.env.AWS_ACCESS_KEY_ID) {
|
||||
process.env.AWS_ACCESS_KEY_ID = process.env.AWS_KEY
|
||||
}
|
||||
if (process.env.AWS_SECRET && !process.env.AWS_SECRET_ACCESS_KEY) {
|
||||
process.env.AWS_SECRET_ACCESS_KEY = process.env.AWS_SECRET
|
||||
}
|
||||
|
||||
// pre-backend setting, fall back to old behaviour
|
||||
if (process.env.BACKEND == null) {
|
||||
if (process.env.AWS_ACCESS_KEY_ID || process.env.S3_BUCKET_CREDENTIALS) {
|
||||
process.env.BACKEND = 's3'
|
||||
process.env.USER_FILES_BUCKET_NAME =
|
||||
process.env.AWS_S3_USER_FILES_BUCKET_NAME
|
||||
process.env.TEMPLATE_FILES_BUCKET_NAME =
|
||||
process.env.AWS_S3_TEMPLATE_FILES_BUCKET_NAME
|
||||
process.env.PUBLIC_FILES_BUCKET_NAME =
|
||||
process.env.AWS_S3_PUBLIC_FILES_BUCKET_NAME
|
||||
} else {
|
||||
process.env.BACKEND = 'fs'
|
||||
process.env.USER_FILES_BUCKET_NAME = Path.resolve(
|
||||
// eslint-disable-next-line no-path-concat
|
||||
__dirname + '/../user_files'
|
||||
)
|
||||
process.env.TEMPLATE_FILES_BUCKET_NAME = Path.resolve(
|
||||
// eslint-disable-next-line no-path-concat
|
||||
__dirname + '/../template_files'
|
||||
)
|
||||
process.env.PUBLIC_FILES_BUCKET_NAME = Path.resolve(
|
||||
// eslint-disable-next-line no-path-concat
|
||||
__dirname + '/../public_files'
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
const settings = {
|
||||
internal: {
|
||||
filestore: {
|
||||
port: 3009,
|
||||
host: process.env.LISTEN_ADDRESS || 'localhost',
|
||||
},
|
||||
},
|
||||
|
||||
filestore: {
|
||||
// Which backend persistor to use.
|
||||
// Choices are
|
||||
// s3 - Amazon S3
|
||||
// fs - local filesystem
|
||||
// gcs - Google Cloud Storage
|
||||
backend: process.env.BACKEND,
|
||||
|
||||
gcs: {
|
||||
endpoint: process.env.GCS_API_ENDPOINT
|
||||
? {
|
||||
apiEndpoint: process.env.GCS_API_ENDPOINT,
|
||||
apiScheme: process.env.GCS_API_SCHEME,
|
||||
projectId: process.env.GCS_PROJECT_ID,
|
||||
}
|
||||
: undefined,
|
||||
unlockBeforeDelete: process.env.GCS_UNLOCK_BEFORE_DELETE === 'true', // unlock an event-based hold before deleting. default false
|
||||
deletedBucketSuffix: process.env.GCS_DELETED_BUCKET_SUFFIX, // if present, copy file to another bucket on delete. default null
|
||||
deleteConcurrency: parseInt(process.env.GCS_DELETE_CONCURRENCY) || 50,
|
||||
signedUrlExpiryInMs: parseInt(process.env.LINK_EXPIRY_TIMEOUT || 60000),
|
||||
},
|
||||
|
||||
s3:
|
||||
process.env.AWS_ACCESS_KEY_ID || process.env.S3_BUCKET_CREDENTIALS
|
||||
? {
|
||||
key: process.env.AWS_ACCESS_KEY_ID,
|
||||
secret: process.env.AWS_SECRET_ACCESS_KEY,
|
||||
endpoint: process.env.AWS_S3_ENDPOINT,
|
||||
pathStyle: process.env.AWS_S3_PATH_STYLE,
|
||||
partSize: process.env.AWS_S3_PARTSIZE || 100 * 1024 * 1024,
|
||||
bucketCreds: process.env.S3_BUCKET_CREDENTIALS
|
||||
? JSON.parse(process.env.S3_BUCKET_CREDENTIALS)
|
||||
: undefined,
|
||||
}
|
||||
: undefined,
|
||||
|
||||
// GCS should be configured by the service account on the kubernetes pod. See GOOGLE_APPLICATION_CREDENTIALS,
|
||||
// which will be picked up automatically.
|
||||
|
||||
stores: {
|
||||
user_files: process.env.USER_FILES_BUCKET_NAME,
|
||||
template_files: process.env.TEMPLATE_FILES_BUCKET_NAME,
|
||||
public_files: process.env.PUBLIC_FILES_BUCKET_NAME,
|
||||
},
|
||||
|
||||
fallback: process.env.FALLBACK_BACKEND
|
||||
? {
|
||||
backend: process.env.FALLBACK_BACKEND,
|
||||
// mapping of bucket names on the fallback, to bucket names on the primary.
|
||||
// e.g. { myS3UserFilesBucketName: 'myGoogleUserFilesBucketName' }
|
||||
buckets: JSON.parse(process.env.FALLBACK_BUCKET_MAPPING || '{}'),
|
||||
copyOnMiss: process.env.COPY_ON_MISS === 'true',
|
||||
}
|
||||
: undefined,
|
||||
|
||||
allowRedirects: process.env.ALLOW_REDIRECTS === 'true',
|
||||
},
|
||||
|
||||
path: {
|
||||
// eslint-disable-next-line no-path-concat
|
||||
uploadFolder: Path.resolve(__dirname + '/../uploads'),
|
||||
},
|
||||
|
||||
commands: {
|
||||
// Any commands to wrap the convert utility in, for example ["nice"], or ["firejail", "--profile=/etc/firejail/convert.profile"]
|
||||
convertCommandPrefix: [],
|
||||
},
|
||||
|
||||
enableConversions: process.env.ENABLE_CONVERSIONS === 'true',
|
||||
|
||||
sentry: {
|
||||
dsn: process.env.SENTRY_DSN,
|
||||
},
|
||||
}
|
||||
|
||||
// Filestore health check
|
||||
// ----------------------
|
||||
// Project and file details to check in persistor when calling /health_check
|
||||
if (process.env.HEALTH_CHECK_PROJECT_ID && process.env.HEALTH_CHECK_FILE_ID) {
|
||||
settings.health_check = {
|
||||
project_id: process.env.HEALTH_CHECK_PROJECT_ID,
|
||||
file_id: process.env.HEALTH_CHECK_FILE_ID,
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = settings
|
75
services/filestore/docker-compose.ci.yml
Normal file
75
services/filestore/docker-compose.ci.yml
Normal file
|
@ -0,0 +1,75 @@
|
|||
# This file was auto-generated, do not edit it directly.
|
||||
# Instead run bin/update_build_scripts from
|
||||
# https://github.com/sharelatex/sharelatex-dev-environment
|
||||
|
||||
version: "2.3"
|
||||
|
||||
services:
|
||||
test_unit:
|
||||
image: ci/$PROJECT_NAME:$BRANCH_NAME-$BUILD_NUMBER
|
||||
user: node
|
||||
command: npm run test:unit:_run
|
||||
environment:
|
||||
NODE_ENV: test
|
||||
NODE_OPTIONS: "--unhandled-rejections=strict"
|
||||
|
||||
|
||||
test_acceptance:
|
||||
build: .
|
||||
image: ci/$PROJECT_NAME:$BRANCH_NAME-$BUILD_NUMBER
|
||||
environment:
|
||||
ELASTIC_SEARCH_DSN: es:9200
|
||||
REDIS_HOST: redis
|
||||
QUEUES_REDIS_HOST: redis
|
||||
MONGO_HOST: mongo
|
||||
POSTGRES_HOST: postgres
|
||||
AWS_S3_ENDPOINT: http://s3:9090
|
||||
AWS_S3_PATH_STYLE: 'true'
|
||||
AWS_ACCESS_KEY_ID: fake
|
||||
AWS_SECRET_ACCESS_KEY: fake
|
||||
GCS_API_ENDPOINT: gcs:9090
|
||||
GCS_API_SCHEME: http
|
||||
GCS_PROJECT_ID: fake
|
||||
STORAGE_EMULATOR_HOST: http://gcs:9090/storage/v1
|
||||
MOCHA_GREP: ${MOCHA_GREP}
|
||||
NODE_ENV: test
|
||||
NODE_OPTIONS: "--unhandled-rejections=strict"
|
||||
ENABLE_CONVERSIONS: "true"
|
||||
USE_PROM_METRICS: "true"
|
||||
AWS_S3_USER_FILES_BUCKET_NAME: fake_user_files
|
||||
AWS_S3_TEMPLATE_FILES_BUCKET_NAME: fake_template_files
|
||||
AWS_S3_PUBLIC_FILES_BUCKET_NAME: fake_public_files
|
||||
GCS_USER_FILES_BUCKET_NAME: fake_userfiles
|
||||
GCS_TEMPLATE_FILES_BUCKET_NAME: fake_templatefiles
|
||||
GCS_PUBLIC_FILES_BUCKET_NAME: fake_publicfiles
|
||||
depends_on:
|
||||
s3:
|
||||
condition: service_healthy
|
||||
gcs:
|
||||
condition: service_healthy
|
||||
user: node
|
||||
command: npm run test:acceptance:_run
|
||||
|
||||
|
||||
tar:
|
||||
build: .
|
||||
image: ci/$PROJECT_NAME:$BRANCH_NAME-$BUILD_NUMBER
|
||||
volumes:
|
||||
- ./:/tmp/build/
|
||||
command: tar -czf /tmp/build/build.tar.gz --exclude=build.tar.gz --exclude-vcs .
|
||||
user: root
|
||||
s3:
|
||||
image: adobe/s3mock
|
||||
environment:
|
||||
- initialBuckets=fake_user_files,fake_template_files,fake_public_files,bucket
|
||||
healthcheck:
|
||||
test: wget --quiet --output-document=/dev/null http://localhost:9090
|
||||
interval: 1s
|
||||
retries: 20
|
||||
gcs:
|
||||
image: fsouza/fake-gcs-server:v1.21.2
|
||||
command: ["--port=9090", "--scheme=http"]
|
||||
healthcheck:
|
||||
test: wget --quiet --output-document=/dev/null http://localhost:9090/storage/v1/b
|
||||
interval: 1s
|
||||
retries: 20
|
77
services/filestore/docker-compose.yml
Normal file
77
services/filestore/docker-compose.yml
Normal file
|
@ -0,0 +1,77 @@
|
|||
# This file was auto-generated, do not edit it directly.
|
||||
# Instead run bin/update_build_scripts from
|
||||
# https://github.com/sharelatex/sharelatex-dev-environment
|
||||
|
||||
version: "2.3"
|
||||
|
||||
services:
|
||||
test_unit:
|
||||
build:
|
||||
context: .
|
||||
target: base
|
||||
volumes:
|
||||
- .:/app
|
||||
working_dir: /app
|
||||
environment:
|
||||
MOCHA_GREP: ${MOCHA_GREP}
|
||||
NODE_ENV: test
|
||||
NODE_OPTIONS: "--unhandled-rejections=strict"
|
||||
command: npm run --silent test:unit
|
||||
user: node
|
||||
|
||||
test_acceptance:
|
||||
build:
|
||||
context: .
|
||||
target: base
|
||||
volumes:
|
||||
- .:/app
|
||||
working_dir: /app
|
||||
environment:
|
||||
ELASTIC_SEARCH_DSN: es:9200
|
||||
REDIS_HOST: redis
|
||||
QUEUES_REDIS_HOST: redis
|
||||
MONGO_HOST: mongo
|
||||
POSTGRES_HOST: postgres
|
||||
AWS_S3_ENDPOINT: http://s3:9090
|
||||
AWS_S3_PATH_STYLE: 'true'
|
||||
AWS_ACCESS_KEY_ID: fake
|
||||
AWS_SECRET_ACCESS_KEY: fake
|
||||
GCS_API_ENDPOINT: gcs:9090
|
||||
GCS_API_SCHEME: http
|
||||
GCS_PROJECT_ID: fake
|
||||
STORAGE_EMULATOR_HOST: http://gcs:9090/storage/v1
|
||||
MOCHA_GREP: ${MOCHA_GREP}
|
||||
LOG_LEVEL: ERROR
|
||||
NODE_ENV: test
|
||||
NODE_OPTIONS: "--unhandled-rejections=strict"
|
||||
ENABLE_CONVERSIONS: "true"
|
||||
USE_PROM_METRICS: "true"
|
||||
AWS_S3_USER_FILES_BUCKET_NAME: fake_user_files
|
||||
AWS_S3_TEMPLATE_FILES_BUCKET_NAME: fake_template_files
|
||||
AWS_S3_PUBLIC_FILES_BUCKET_NAME: fake_public_files
|
||||
GCS_USER_FILES_BUCKET_NAME: fake_userfiles
|
||||
GCS_TEMPLATE_FILES_BUCKET_NAME: fake_templatefiles
|
||||
GCS_PUBLIC_FILES_BUCKET_NAME: fake_publicfiles
|
||||
user: node
|
||||
depends_on:
|
||||
s3:
|
||||
condition: service_healthy
|
||||
gcs:
|
||||
condition: service_healthy
|
||||
command: npm run --silent test:acceptance
|
||||
|
||||
s3:
|
||||
image: adobe/s3mock
|
||||
environment:
|
||||
- initialBuckets=fake_user_files,fake_template_files,fake_public_files,bucket
|
||||
healthcheck:
|
||||
test: wget --quiet --output-document=/dev/null http://localhost:9090
|
||||
interval: 1s
|
||||
retries: 20
|
||||
gcs:
|
||||
image: fsouza/fake-gcs-server:v1.21.2
|
||||
command: ["--port=9090", "--scheme=http"]
|
||||
healthcheck:
|
||||
test: wget --quiet --output-document=/dev/null http://localhost:9090/storage/v1/b
|
||||
interval: 1s
|
||||
retries: 20
|
40
services/filestore/firejail/convert.profile
Normal file
40
services/filestore/firejail/convert.profile
Normal file
|
@ -0,0 +1,40 @@
|
|||
# Convert (ImageMagick profile)
|
||||
|
||||
include /etc/firejail/disable-common.inc
|
||||
include /etc/firejail/disable-devel.inc
|
||||
# include /etc/firejail/disable-mgmt.inc ## removed in firejail 0.9.40
|
||||
# include /etc/firejail/disable-secret.inc ## removed in firejail 0.9.40
|
||||
|
||||
read-only /bin
|
||||
blacklist /boot
|
||||
blacklist /dev
|
||||
read-only /etc
|
||||
read-only /home
|
||||
read-only /lib
|
||||
read-only /lib64
|
||||
blacklist /media
|
||||
blacklist /mnt
|
||||
blacklist /opt
|
||||
blacklist /root
|
||||
read-only /run
|
||||
blacklist /sbin
|
||||
blacklist /selinux
|
||||
blacklist /src
|
||||
blacklist /sys
|
||||
read-only /usr
|
||||
blacklist /var
|
||||
|
||||
caps.drop all
|
||||
noroot
|
||||
nogroups
|
||||
protocol unix
|
||||
net none
|
||||
private-tmp
|
||||
private-dev
|
||||
shell none
|
||||
|
||||
seccomp.keep accept,accept4,access,alarm,arch_prctl,bind,brk,capget,capset,chdir,chmod,chown,chroot,clock_getres,clock_gettime,clock_nanosleep,clone,close,connect,creat,dup,dup2,dup3,epoll_create,epoll_create1,epoll_ctl,epoll_ctl_old,epoll_pwait,epoll_wait,epoll_wait_old,eventfd,eventfd2,execve,execveat,exit,exit_group,faccessat,fadvise64,fallocate,fanotify_init,fanotify_mark,fchdir,fchmod,fchmodat,fchown,fchownat,fcntl,fdatasync,fgetxattr,flistxattr,flock,fork,fremovexattr,fsetxattr,fstat,fstatfs,fsync,ftruncate,futex,futimesat,get_robust_list,get_thread_area,getcpu,getcwd,getdents,getdents64,getegid,geteuid,getgid,getgroups,getitimer,getpeername,getpgid,getpgrp,getpid,getppid,getpriority,getrandom,getresgid,getresuid,getrlimit,getrusage,getsid,getsockname,getsockopt,gettid,gettimeofday,getuid,getxattr,inotify_add_watch,inotify_init,inotify_init1,inotify_rm_watch,io_cancel,io_destroy,io_getevents,io_setup,io_submit,ioctl,ioprio_get,ioprio_set,kill,lchown,lgetxattr,link,linkat,listen,listxattr,llistxattr,lremovexattr,lseek,lsetxattr,lstat,madvise,memfd_create,mincore,mkdir,mkdirat,mknod,mknodat,mlock,mlockall,mmap,modify_ldt,mprotect,mq_getsetattr,mq_notify,mq_open,mq_timedreceive,mq_timedsend,mq_unlink,mremap,msgctl,msgget,msgrcv,msgsnd,msync,munlock,munlockall,munmap,nanosleep,newfstatat,open,openat,pause,personality,pipe,pipe2,poll,ppoll,prctl,pread64,preadv,prlimit64,pselect6,pwrite64,pwritev,read,readahead,readlink,readlinkat,readv,recvfrom,recvmmsg,recvmsg,remap_file_pages,removexattr,rename,renameat,renameat2,restart_syscall,rmdir,rt_sigaction,rt_sigpending,rt_sigprocmask,rt_sigqueueinfo,rt_sigreturn,rt_sigsuspend,rt_sigtimedwait,rt_tgsigqueueinfo,sched_get_priority_max,sched_get_priority_min,sched_getaffinity,sched_getattr,sched_getparam,sched_getscheduler,sched_rr_get_interval,sched_setaffinity,sched_setattr,sched_setparam,sched_setscheduler,sched_yield,seccomp,select,semctl,semget,semop,semtimedop,sendfile,sendmmsg,sendmsg,sendto,set_robust_list,set_thread_area,set_tid_address,setdomainname,setfsgid,setfsuid,setgid,setgroups,sethostname,setitimer,setpgid,setpriority,setregid,setresgid,setresuid,setreuid,setrlimit,setsid,setsockopt,setuid,setxattr,shmat,shmctl,shmdt,shmget,shutdown,sigaltstack,signalfd,signalfd4,socket,socketpair,splice,stat,statfs,symlink,symlinkat,sync,sync_file_range,syncfs,sysinfo,syslog,tee,tgkill,time,timer_create,timer_delete,timer_getoverrun,timer_gettime,timer_settime,timerfd_create,timerfd_gettime,timerfd_settime,times,tkill,truncate,umask,uname,unlink,unlinkat,utime,utimensat,utimes,vfork,vhangup,vmsplice,wait4,waitid,write,writev,unshare
|
||||
|
||||
rlimit-fsize 524288000 #500Mb
|
||||
rlimit-nproc 600 #if too low this can cause error: Error fork:sandbox(774): Resource temporarily unavailable
|
||||
rlimit-nofile 100
|
9
services/filestore/install_deps.sh
Executable file
9
services/filestore/install_deps.sh
Executable file
|
@ -0,0 +1,9 @@
|
|||
#!/bin/sh
|
||||
|
||||
set -ex
|
||||
|
||||
apt-get update
|
||||
|
||||
apt-get install ghostscript imagemagick optipng --yes
|
||||
|
||||
rm -rf /var/lib/apt/lists/*
|
17
services/filestore/nodemon.json
Normal file
17
services/filestore/nodemon.json
Normal file
|
@ -0,0 +1,17 @@
|
|||
{
|
||||
"ignore": [
|
||||
".git",
|
||||
"node_modules/"
|
||||
],
|
||||
"verbose": true,
|
||||
"legacyWatch": true,
|
||||
"execMap": {
|
||||
"js": "npm run start"
|
||||
},
|
||||
"watch": [
|
||||
"app/js/",
|
||||
"app.js",
|
||||
"config/"
|
||||
],
|
||||
"ext": "js"
|
||||
}
|
7021
services/filestore/package-lock.json
generated
Normal file
7021
services/filestore/package-lock.json
generated
Normal file
File diff suppressed because it is too large
Load diff
68
services/filestore/package.json
Normal file
68
services/filestore/package.json
Normal file
|
@ -0,0 +1,68 @@
|
|||
{
|
||||
"name": "filestore-sharelatex",
|
||||
"version": "0.1.4",
|
||||
"description": "An API for CRUD operations on binary files stored in S3",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/sharelatex/filestore-sharelatex.git"
|
||||
},
|
||||
"scripts": {
|
||||
"test:acceptance:run": "mocha --recursive --reporter spec --timeout 15000 $@ test/acceptance/js",
|
||||
"test:acceptance": "npm run test:acceptance:_run -- --grep=$MOCHA_GREP",
|
||||
"test:unit:run": "mocha --recursive --reporter spec $@ test/unit/js",
|
||||
"test:unit": "npm run test:unit:_run -- --grep=$MOCHA_GREP",
|
||||
"start": "node $NODE_APP_OPTIONS app.js",
|
||||
"nodemon": "nodemon --config nodemon.json",
|
||||
"lint": "eslint --max-warnings 0 --format unix .",
|
||||
"format": "prettier --list-different $PWD/'**/*.js'",
|
||||
"format:fix": "prettier --write $PWD/'**/*.js'",
|
||||
"test:acceptance:_run": "mocha --recursive --reporter spec --timeout 15000 --exit $@ test/acceptance/js",
|
||||
"test:unit:_run": "mocha --recursive --reporter spec $@ test/unit/js",
|
||||
"lint:fix": "eslint --fix ."
|
||||
},
|
||||
"dependencies": {
|
||||
"@overleaf/metrics": "^3.5.1",
|
||||
"@overleaf/o-error": "^3.0.0",
|
||||
"@overleaf/object-persistor": "https://github.com/overleaf/object-persistor/archive/8fbc9ed03206bfb54368578d22b7ac4f285baa25.tar.gz",
|
||||
"@overleaf/settings": "^2.1.1",
|
||||
"body-parser": "^1.19.0",
|
||||
"bunyan": "^1.8.15",
|
||||
"express": "^4.17.1",
|
||||
"fast-crc32c": "^2.0.0",
|
||||
"glob": "^7.1.6",
|
||||
"lodash.once": "^4.1.1",
|
||||
"logger-sharelatex": "^2.2.0",
|
||||
"node-uuid": "~1.4.8",
|
||||
"range-parser": "^1.2.1",
|
||||
"request": "^2.88.2",
|
||||
"request-promise-native": "^1.0.8",
|
||||
"stream-buffers": "~0.2.6",
|
||||
"tiny-async-pool": "^1.1.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@google-cloud/storage": "^5.1.2",
|
||||
"aws-sdk": "^2.718.0",
|
||||
"chai": "^4.2.0",
|
||||
"chai-as-promised": "^7.1.1",
|
||||
"disrequire": "^1.1.0",
|
||||
"eslint": "^7.21.0",
|
||||
"eslint-config-prettier": "^8.1.0",
|
||||
"eslint-config-standard": "^16.0.2",
|
||||
"eslint-plugin-chai-expect": "^2.2.0",
|
||||
"eslint-plugin-chai-friendly": "^0.6.0",
|
||||
"eslint-plugin-import": "^2.22.1",
|
||||
"eslint-plugin-mocha": "^8.0.0",
|
||||
"eslint-plugin-node": "^11.1.0",
|
||||
"eslint-plugin-prettier": "^3.1.2",
|
||||
"eslint-plugin-promise": "^4.2.1",
|
||||
"mocha": "^8.3.2",
|
||||
"mongodb": "^3.5.9",
|
||||
"prettier": "^2.2.1",
|
||||
"prettier-eslint": "^9.0.2",
|
||||
"sandboxed-module": "2.0.4",
|
||||
"sinon": "9.0.2",
|
||||
"sinon-chai": "^3.5.0",
|
||||
"streamifier": "^0.1.1",
|
||||
"timekeeper": "^2.2.0"
|
||||
}
|
||||
}
|
0
services/filestore/template_files/.gitignore
vendored
Normal file
0
services/filestore/template_files/.gitignore
vendored
Normal file
|
@ -0,0 +1,5 @@
|
|||
FROM fsouza/fake-gcs-server:1.20
|
||||
RUN apk add --update --no-cache curl
|
||||
COPY healthcheck.sh /healthcheck.sh
|
||||
HEALTHCHECK --interval=1s --timeout=1s --retries=30 CMD /healthcheck.sh http://localhost:9090
|
||||
CMD ["--port=9090", "--scheme=http"]
|
|
@ -0,0 +1,4 @@
|
|||
FROM adobe/s3mock
|
||||
RUN apk add --update --no-cache curl
|
||||
COPY healthcheck.sh /healthcheck.sh
|
||||
HEALTHCHECK --interval=1s --timeout=1s --retries=30 CMD /healthcheck.sh http://localhost:9090
|
9
services/filestore/test/acceptance/deps/healthcheck.sh
Executable file
9
services/filestore/test/acceptance/deps/healthcheck.sh
Executable file
|
@ -0,0 +1,9 @@
|
|||
#!/bin/sh
|
||||
|
||||
# health check to allow 404 status code as valid
|
||||
STATUSCODE=$(curl --silent --output /dev/null --write-out "%{http_code}" $1)
|
||||
# will be 000 on non-http error (e.g. connection failure)
|
||||
if test $STATUSCODE -ge 500 || test $STATUSCODE -lt 200; then
|
||||
exit 1
|
||||
fi
|
||||
exit 0
|
123
services/filestore/test/acceptance/js/FilestoreApp.js
Normal file
123
services/filestore/test/acceptance/js/FilestoreApp.js
Normal file
|
@ -0,0 +1,123 @@
|
|||
const logger = require('logger-sharelatex')
|
||||
const Settings = require('@overleaf/settings')
|
||||
const fs = require('fs')
|
||||
const Path = require('path')
|
||||
const { promisify } = require('util')
|
||||
const disrequire = require('disrequire')
|
||||
const AWS = require('aws-sdk')
|
||||
|
||||
logger.logger.level('info')
|
||||
|
||||
const fsReaddir = promisify(fs.readdir)
|
||||
const sleep = promisify(setTimeout)
|
||||
|
||||
class FilestoreApp {
|
||||
constructor() {
|
||||
this.running = false
|
||||
this.initing = false
|
||||
}
|
||||
|
||||
async runServer() {
|
||||
if (this.running) {
|
||||
return
|
||||
}
|
||||
|
||||
if (this.initing) {
|
||||
return this.waitForInit()
|
||||
}
|
||||
this.initing = true
|
||||
|
||||
this.app = await FilestoreApp.requireApp()
|
||||
|
||||
await new Promise((resolve, reject) => {
|
||||
this.server = this.app.listen(
|
||||
Settings.internal.filestore.port,
|
||||
'localhost',
|
||||
err => {
|
||||
if (err) {
|
||||
return reject(err)
|
||||
}
|
||||
resolve()
|
||||
}
|
||||
)
|
||||
})
|
||||
|
||||
if (Settings.filestore.backend === 's3') {
|
||||
try {
|
||||
await FilestoreApp.waitForS3()
|
||||
} catch (err) {
|
||||
await this.stop()
|
||||
throw err
|
||||
}
|
||||
}
|
||||
|
||||
this.initing = false
|
||||
this.persistor = require('../../../app/js/PersistorManager')
|
||||
}
|
||||
|
||||
async waitForInit() {
|
||||
while (this.initing) {
|
||||
await sleep(1000)
|
||||
}
|
||||
}
|
||||
|
||||
async stop() {
|
||||
if (!this.server) return
|
||||
const closeServer = promisify(this.server.close).bind(this.server)
|
||||
try {
|
||||
await closeServer()
|
||||
} finally {
|
||||
delete this.server
|
||||
}
|
||||
}
|
||||
|
||||
static async waitForS3() {
|
||||
let tries = 0
|
||||
if (!Settings.filestore.s3.endpoint) {
|
||||
return
|
||||
}
|
||||
|
||||
const s3 = new AWS.S3({
|
||||
accessKeyId: Settings.filestore.s3.key,
|
||||
secretAccessKey: Settings.filestore.s3.secret,
|
||||
endpoint: Settings.filestore.s3.endpoint,
|
||||
s3ForcePathStyle: true,
|
||||
signatureVersion: 'v4',
|
||||
})
|
||||
|
||||
while (true) {
|
||||
try {
|
||||
return await s3
|
||||
.putObject({
|
||||
Key: 'startup',
|
||||
Body: '42',
|
||||
Bucket: Settings.filestore.stores.user_files,
|
||||
})
|
||||
.promise()
|
||||
} catch (err) {
|
||||
// swallow errors, as we may experience them until fake-s3 is running
|
||||
if (tries === 9) {
|
||||
// throw just before hitting the 10s test timeout
|
||||
throw err
|
||||
}
|
||||
tries++
|
||||
await sleep(1000)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static async requireApp() {
|
||||
// unload the app, as we may be doing this on multiple runs with
|
||||
// different settings, which affect startup in some cases
|
||||
const files = await fsReaddir(Path.resolve(__dirname, '../../../app/js'))
|
||||
files.forEach(file => {
|
||||
disrequire(Path.resolve(__dirname, '../../../app/js', file))
|
||||
})
|
||||
disrequire(Path.resolve(__dirname, '../../../app'))
|
||||
disrequire('@overleaf/object-persistor')
|
||||
|
||||
return require('../../../app')
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = FilestoreApp
|
932
services/filestore/test/acceptance/js/FilestoreTests.js
Normal file
932
services/filestore/test/acceptance/js/FilestoreTests.js
Normal file
|
@ -0,0 +1,932 @@
|
|||
const chai = require('chai')
|
||||
const { expect } = chai
|
||||
const fs = require('fs')
|
||||
const Settings = require('@overleaf/settings')
|
||||
const Path = require('path')
|
||||
const FilestoreApp = require('./FilestoreApp')
|
||||
const TestHelper = require('./TestHelper')
|
||||
const rp = require('request-promise-native').defaults({
|
||||
resolveWithFullResponse: true,
|
||||
})
|
||||
const S3 = require('aws-sdk/clients/s3')
|
||||
const Stream = require('stream')
|
||||
const request = require('request')
|
||||
const { promisify } = require('util')
|
||||
const { Storage } = require('@google-cloud/storage')
|
||||
const streamifier = require('streamifier')
|
||||
chai.use(require('chai-as-promised'))
|
||||
const { ObjectId } = require('mongodb')
|
||||
const tk = require('timekeeper')
|
||||
const ChildProcess = require('child_process')
|
||||
|
||||
const fsWriteFile = promisify(fs.writeFile)
|
||||
const fsStat = promisify(fs.stat)
|
||||
const pipeline = promisify(Stream.pipeline)
|
||||
const exec = promisify(ChildProcess.exec)
|
||||
const msleep = promisify(setTimeout)
|
||||
|
||||
if (!process.env.AWS_ACCESS_KEY_ID) {
|
||||
throw new Error('please provide credentials for the AWS S3 test server')
|
||||
}
|
||||
|
||||
process.on('unhandledRejection', e => {
|
||||
// eslint-disable-next-line no-console
|
||||
console.log('** Unhandled Promise Rejection **\n', e)
|
||||
throw e
|
||||
})
|
||||
|
||||
// store settings for multiple backends, so that we can test each one.
|
||||
// fs will always be available - add others if they are configured
|
||||
const BackendSettings = require('./TestConfig')
|
||||
|
||||
describe('Filestore', function () {
|
||||
this.timeout(1000 * 10)
|
||||
const filestoreUrl = `http://localhost:${Settings.internal.filestore.port}`
|
||||
|
||||
const seenSockets = []
|
||||
async function expectNoSockets() {
|
||||
try {
|
||||
await msleep(1000)
|
||||
const { stdout } = await exec('ss -tnH')
|
||||
|
||||
const badSockets = []
|
||||
for (const socket of stdout.split('\n')) {
|
||||
const fields = socket.split(' ').filter(part => part !== '')
|
||||
if (
|
||||
fields.length > 2 &&
|
||||
parseInt(fields[1]) &&
|
||||
!seenSockets.includes(socket)
|
||||
) {
|
||||
badSockets.push(socket)
|
||||
seenSockets.push(socket)
|
||||
}
|
||||
}
|
||||
|
||||
if (badSockets.length) {
|
||||
// eslint-disable-next-line no-console
|
||||
console.error(
|
||||
'ERR: Sockets still have receive buffer after connection closed'
|
||||
)
|
||||
for (const socket of badSockets) {
|
||||
// eslint-disable-next-line no-console
|
||||
console.error(socket)
|
||||
}
|
||||
throw new Error('Sockets still open after connection closed')
|
||||
}
|
||||
} catch (err) {
|
||||
expect(err).not.to.exist
|
||||
}
|
||||
}
|
||||
|
||||
// redefine the test suite for every available backend
|
||||
Object.keys(BackendSettings).forEach(backend => {
|
||||
describe(backend, function () {
|
||||
let app, previousEgress, previousIngress, metricPrefix, projectId
|
||||
|
||||
before(async function () {
|
||||
// create the app with the relevant filestore settings
|
||||
Settings.filestore = BackendSettings[backend]
|
||||
app = new FilestoreApp()
|
||||
await app.runServer()
|
||||
})
|
||||
|
||||
if (BackendSettings[backend].gcs) {
|
||||
before(async function () {
|
||||
const storage = new Storage(Settings.filestore.gcs.endpoint)
|
||||
await storage.createBucket(process.env.GCS_USER_FILES_BUCKET_NAME)
|
||||
await storage.createBucket(process.env.GCS_PUBLIC_FILES_BUCKET_NAME)
|
||||
await storage.createBucket(process.env.GCS_TEMPLATE_FILES_BUCKET_NAME)
|
||||
await storage.createBucket(
|
||||
`${process.env.GCS_USER_FILES_BUCKET_NAME}-deleted`
|
||||
)
|
||||
await storage.createBucket(
|
||||
`${process.env.GCS_PUBLIC_FILES_BUCKET_NAME}-deleted`
|
||||
)
|
||||
await storage.createBucket(
|
||||
`${process.env.GCS_TEMPLATE_FILES_BUCKET_NAME}-deleted`
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
after(async function () {
|
||||
await msleep(3000)
|
||||
await app.stop()
|
||||
})
|
||||
|
||||
beforeEach(async function () {
|
||||
// retrieve previous metrics from the app
|
||||
if (['s3', 'gcs'].includes(Settings.filestore.backend)) {
|
||||
metricPrefix = Settings.filestore.backend
|
||||
previousEgress = await TestHelper.getMetric(
|
||||
filestoreUrl,
|
||||
`${metricPrefix}_egress`
|
||||
)
|
||||
}
|
||||
projectId = ObjectId().toString()
|
||||
})
|
||||
|
||||
it('should send a 200 for the status endpoint', async function () {
|
||||
const response = await rp(`${filestoreUrl}/status`)
|
||||
expect(response.statusCode).to.equal(200)
|
||||
expect(response.body).to.contain('filestore')
|
||||
expect(response.body).to.contain('up')
|
||||
})
|
||||
|
||||
it('should send a 200 for the health-check endpoint', async function () {
|
||||
const response = await rp(`${filestoreUrl}/health_check`)
|
||||
expect(response.statusCode).to.equal(200)
|
||||
expect(response.body).to.equal('OK')
|
||||
})
|
||||
|
||||
describe('with a file on the server', function () {
|
||||
let fileId, fileUrl, constantFileContent
|
||||
|
||||
const localFileReadPath =
|
||||
'/tmp/filestore_acceptance_tests_file_read.txt'
|
||||
|
||||
beforeEach(async function () {
|
||||
fileId = ObjectId().toString()
|
||||
fileUrl = `${filestoreUrl}/project/${projectId}/file/${fileId}`
|
||||
constantFileContent = [
|
||||
'hello world',
|
||||
`line 2 goes here ${Math.random()}`,
|
||||
'there are 3 lines in all',
|
||||
].join('\n')
|
||||
|
||||
await fsWriteFile(localFileReadPath, constantFileContent)
|
||||
|
||||
const writeStream = request.post(fileUrl)
|
||||
const readStream = fs.createReadStream(localFileReadPath)
|
||||
// hack to consume the result to ensure the http request has been fully processed
|
||||
const resultStream = fs.createWriteStream('/dev/null')
|
||||
await pipeline(readStream, writeStream, resultStream)
|
||||
})
|
||||
|
||||
beforeEach(async function retrievePreviousIngressMetrics() {
|
||||
// The upload request can bump the ingress metric.
|
||||
// The content hash validation might require a full download
|
||||
// in case the ETag field of the upload response is not a md5 sum.
|
||||
if (['s3', 'gcs'].includes(Settings.filestore.backend)) {
|
||||
previousIngress = await TestHelper.getMetric(
|
||||
filestoreUrl,
|
||||
`${metricPrefix}_ingress`
|
||||
)
|
||||
}
|
||||
})
|
||||
|
||||
it('should return 404 for a non-existant id', async function () {
|
||||
const options = { uri: fileUrl + '___this_is_clearly_wrong___' }
|
||||
await expect(
|
||||
rp.get(options)
|
||||
).to.eventually.be.rejected.and.have.property('statusCode', 404)
|
||||
})
|
||||
|
||||
it('should return the file size on a HEAD request', async function () {
|
||||
const expectedLength = Buffer.byteLength(constantFileContent)
|
||||
const res = await rp.head(fileUrl)
|
||||
expect(res.statusCode).to.equal(200)
|
||||
expect(res.headers['content-length']).to.equal(
|
||||
expectedLength.toString()
|
||||
)
|
||||
})
|
||||
|
||||
it('should be able get the file back', async function () {
|
||||
const res = await rp.get(fileUrl)
|
||||
expect(res.body).to.equal(constantFileContent)
|
||||
})
|
||||
|
||||
it('should not leak a socket', async function () {
|
||||
await rp.get(fileUrl)
|
||||
await expectNoSockets()
|
||||
})
|
||||
|
||||
it('should be able to get back the first 9 bytes of the file', async function () {
|
||||
const options = {
|
||||
uri: fileUrl,
|
||||
headers: {
|
||||
Range: 'bytes=0-8',
|
||||
},
|
||||
}
|
||||
const res = await rp.get(options)
|
||||
expect(res.body).to.equal('hello wor')
|
||||
})
|
||||
|
||||
it('should be able to get back bytes 4 through 10 of the file', async function () {
|
||||
const options = {
|
||||
uri: fileUrl,
|
||||
headers: {
|
||||
Range: 'bytes=4-10',
|
||||
},
|
||||
}
|
||||
const res = await rp.get(options)
|
||||
expect(res.body).to.equal('o world')
|
||||
})
|
||||
|
||||
it('should be able to delete the file', async function () {
|
||||
const response = await rp.del(fileUrl)
|
||||
expect(response.statusCode).to.equal(204)
|
||||
await expect(
|
||||
rp.get(fileUrl)
|
||||
).to.eventually.be.rejected.and.have.property('statusCode', 404)
|
||||
})
|
||||
|
||||
it('should be able to copy files', async function () {
|
||||
const newProjectID = ObjectId().toString()
|
||||
const newFileId = ObjectId().toString()
|
||||
const newFileUrl = `${filestoreUrl}/project/${newProjectID}/file/${newFileId}`
|
||||
const opts = {
|
||||
method: 'put',
|
||||
uri: newFileUrl,
|
||||
json: {
|
||||
source: {
|
||||
project_id: projectId,
|
||||
file_id: fileId,
|
||||
},
|
||||
},
|
||||
}
|
||||
let response = await rp(opts)
|
||||
expect(response.statusCode).to.equal(200)
|
||||
response = await rp.del(fileUrl)
|
||||
expect(response.statusCode).to.equal(204)
|
||||
response = await rp.get(newFileUrl)
|
||||
expect(response.body).to.equal(constantFileContent)
|
||||
})
|
||||
|
||||
it('should be able to overwrite the file', async function () {
|
||||
const newContent = `here is some different content, ${Math.random()}`
|
||||
const writeStream = request.post(fileUrl)
|
||||
const readStream = streamifier.createReadStream(newContent)
|
||||
// hack to consume the result to ensure the http request has been fully processed
|
||||
const resultStream = fs.createWriteStream('/dev/null')
|
||||
await pipeline(readStream, writeStream, resultStream)
|
||||
|
||||
const response = await rp.get(fileUrl)
|
||||
expect(response.body).to.equal(newContent)
|
||||
})
|
||||
|
||||
if (['S3Persistor', 'GcsPersistor'].includes(backend)) {
|
||||
it('should record an egress metric for the upload', async function () {
|
||||
const metric = await TestHelper.getMetric(
|
||||
filestoreUrl,
|
||||
`${metricPrefix}_egress`
|
||||
)
|
||||
expect(metric - previousEgress).to.equal(constantFileContent.length)
|
||||
})
|
||||
|
||||
it('should record an ingress metric when downloading the file', async function () {
|
||||
await rp.get(fileUrl)
|
||||
const metric = await TestHelper.getMetric(
|
||||
filestoreUrl,
|
||||
`${metricPrefix}_ingress`
|
||||
)
|
||||
expect(metric - previousIngress).to.equal(
|
||||
constantFileContent.length
|
||||
)
|
||||
})
|
||||
|
||||
it('should record an ingress metric for a partial download', async function () {
|
||||
const options = {
|
||||
uri: fileUrl,
|
||||
headers: {
|
||||
Range: 'bytes=0-8',
|
||||
},
|
||||
}
|
||||
await rp.get(options)
|
||||
const metric = await TestHelper.getMetric(
|
||||
filestoreUrl,
|
||||
`${metricPrefix}_ingress`
|
||||
)
|
||||
expect(metric - previousIngress).to.equal(9)
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
describe('with multiple files', function () {
|
||||
let fileIds, fileUrls, projectUrl
|
||||
const localFileReadPaths = [
|
||||
'/tmp/filestore_acceptance_tests_file_read_1.txt',
|
||||
'/tmp/filestore_acceptance_tests_file_read_2.txt',
|
||||
]
|
||||
const constantFileContents = [
|
||||
[
|
||||
'hello world',
|
||||
`line 2 goes here ${Math.random()}`,
|
||||
'there are 3 lines in all',
|
||||
].join('\n'),
|
||||
[
|
||||
`for reference: ${Math.random()}`,
|
||||
'cats are the best animals',
|
||||
'wombats are a close second',
|
||||
].join('\n'),
|
||||
]
|
||||
|
||||
before(async function () {
|
||||
return Promise.all([
|
||||
fsWriteFile(localFileReadPaths[0], constantFileContents[0]),
|
||||
fsWriteFile(localFileReadPaths[1], constantFileContents[1]),
|
||||
])
|
||||
})
|
||||
|
||||
beforeEach(async function () {
|
||||
projectUrl = `${filestoreUrl}/project/${projectId}`
|
||||
fileIds = [ObjectId().toString(), ObjectId().toString()]
|
||||
fileUrls = [
|
||||
`${projectUrl}/file/${fileIds[0]}`,
|
||||
`${projectUrl}/file/${fileIds[1]}`,
|
||||
]
|
||||
|
||||
const writeStreams = [
|
||||
request.post(fileUrls[0]),
|
||||
request.post(fileUrls[1]),
|
||||
]
|
||||
const readStreams = [
|
||||
fs.createReadStream(localFileReadPaths[0]),
|
||||
fs.createReadStream(localFileReadPaths[1]),
|
||||
]
|
||||
// hack to consume the result to ensure the http request has been fully processed
|
||||
const resultStreams = [
|
||||
fs.createWriteStream('/dev/null'),
|
||||
fs.createWriteStream('/dev/null'),
|
||||
]
|
||||
return Promise.all([
|
||||
pipeline(readStreams[0], writeStreams[0], resultStreams[0]),
|
||||
pipeline(readStreams[1], writeStreams[1], resultStreams[1]),
|
||||
])
|
||||
})
|
||||
|
||||
it('should get the directory size', async function () {
|
||||
const response = await rp.get(
|
||||
`${filestoreUrl}/project/${projectId}/size`
|
||||
)
|
||||
expect(parseInt(JSON.parse(response.body)['total bytes'])).to.equal(
|
||||
constantFileContents[0].length + constantFileContents[1].length
|
||||
)
|
||||
})
|
||||
|
||||
it('should store the files', async function () {
|
||||
for (const index in fileUrls) {
|
||||
await expect(rp.get(fileUrls[index])).to.eventually.have.property(
|
||||
'body',
|
||||
constantFileContents[index]
|
||||
)
|
||||
}
|
||||
})
|
||||
|
||||
it('should be able to delete the project', async function () {
|
||||
await expect(rp.delete(projectUrl)).to.eventually.have.property(
|
||||
'statusCode',
|
||||
204
|
||||
)
|
||||
|
||||
for (const index in fileUrls) {
|
||||
await expect(
|
||||
rp.get(fileUrls[index])
|
||||
).to.eventually.be.rejected.and.have.property('statusCode', 404)
|
||||
}
|
||||
})
|
||||
|
||||
it('should not delete a partial project id', async function () {
|
||||
await expect(
|
||||
rp.delete(`${filestoreUrl}/project/5`)
|
||||
).to.eventually.be.rejected.and.have.property('statusCode', 400)
|
||||
})
|
||||
})
|
||||
|
||||
describe('with a large file', function () {
|
||||
let fileId, fileUrl, largeFileContent, error
|
||||
|
||||
beforeEach(async function () {
|
||||
fileId = ObjectId().toString()
|
||||
fileUrl = `${filestoreUrl}/project/${projectId}/file/${fileId}`
|
||||
|
||||
largeFileContent = '_wombat_'.repeat(1024 * 1024) // 8 megabytes
|
||||
largeFileContent += Math.random()
|
||||
|
||||
const writeStream = request.post(fileUrl)
|
||||
const readStream = streamifier.createReadStream(largeFileContent)
|
||||
// hack to consume the result to ensure the http request has been fully processed
|
||||
const resultStream = fs.createWriteStream('/dev/null')
|
||||
|
||||
try {
|
||||
await pipeline(readStream, writeStream, resultStream)
|
||||
} catch (err) {
|
||||
error = err
|
||||
}
|
||||
})
|
||||
|
||||
it('should be able to get the file back', async function () {
|
||||
const response = await rp.get(fileUrl)
|
||||
expect(response.body).to.equal(largeFileContent)
|
||||
})
|
||||
|
||||
it('should not throw an error', function () {
|
||||
expect(error).not.to.exist
|
||||
})
|
||||
|
||||
it('should not leak a socket', async function () {
|
||||
await rp.get(fileUrl)
|
||||
await expectNoSockets()
|
||||
})
|
||||
|
||||
it('should not leak a socket if the connection is aborted', async function () {
|
||||
this.timeout(20000)
|
||||
for (let i = 0; i < 5; i++) {
|
||||
// test is not 100% reliable, so repeat
|
||||
// create a new connection and have it time out before reading any data
|
||||
await new Promise(resolve => {
|
||||
const streamThatHangs = new Stream.PassThrough()
|
||||
const stream = request({ url: fileUrl, timeout: 1000 })
|
||||
stream.pipe(streamThatHangs)
|
||||
stream.on('error', () => {
|
||||
stream.destroy()
|
||||
streamThatHangs.destroy()
|
||||
resolve()
|
||||
})
|
||||
})
|
||||
await expectNoSockets()
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
if (backend === 'S3Persistor' || backend === 'FallbackGcsToS3Persistor') {
|
||||
describe('with a file in a specific bucket', function () {
|
||||
let constantFileContent, fileId, fileUrl, bucketName
|
||||
|
||||
beforeEach(async function () {
|
||||
constantFileContent = `This is a file in a different S3 bucket ${Math.random()}`
|
||||
fileId = ObjectId().toString()
|
||||
bucketName = ObjectId().toString()
|
||||
fileUrl = `${filestoreUrl}/bucket/${bucketName}/key/${fileId}`
|
||||
|
||||
const s3ClientSettings = {
|
||||
credentials: {
|
||||
accessKeyId: process.env.AWS_ACCESS_KEY_ID,
|
||||
secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY,
|
||||
},
|
||||
endpoint: process.env.AWS_S3_ENDPOINT,
|
||||
sslEnabled: false,
|
||||
s3ForcePathStyle: true,
|
||||
}
|
||||
|
||||
const s3 = new S3(s3ClientSettings)
|
||||
await s3
|
||||
.createBucket({
|
||||
Bucket: bucketName,
|
||||
})
|
||||
.promise()
|
||||
await s3
|
||||
.upload({
|
||||
Bucket: bucketName,
|
||||
Key: fileId,
|
||||
Body: constantFileContent,
|
||||
})
|
||||
.promise()
|
||||
})
|
||||
|
||||
it('should get the file from the specified bucket', async function () {
|
||||
const response = await rp.get(fileUrl)
|
||||
expect(response.body).to.equal(constantFileContent)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
if (backend === 'GcsPersistor') {
|
||||
describe('when deleting a file in GCS', function () {
|
||||
let fileId, fileUrl, content, error, date
|
||||
|
||||
beforeEach(async function () {
|
||||
date = new Date()
|
||||
tk.freeze(date)
|
||||
fileId = ObjectId()
|
||||
fileUrl = `${filestoreUrl}/project/${projectId}/file/${fileId}`
|
||||
|
||||
content = '_wombat_' + Math.random()
|
||||
|
||||
const writeStream = request.post(fileUrl)
|
||||
const readStream = streamifier.createReadStream(content)
|
||||
// hack to consume the result to ensure the http request has been fully processed
|
||||
const resultStream = fs.createWriteStream('/dev/null')
|
||||
|
||||
try {
|
||||
await pipeline(readStream, writeStream, resultStream)
|
||||
await rp.delete(fileUrl)
|
||||
} catch (err) {
|
||||
error = err
|
||||
}
|
||||
})
|
||||
|
||||
afterEach(function () {
|
||||
tk.reset()
|
||||
})
|
||||
|
||||
it('should not throw an error', function () {
|
||||
expect(error).not.to.exist
|
||||
})
|
||||
|
||||
it('should copy the file to the deleted-files bucket', async function () {
|
||||
await TestHelper.expectPersistorToHaveFile(
|
||||
app.persistor,
|
||||
`${Settings.filestore.stores.user_files}-deleted`,
|
||||
`${projectId}/${fileId}-${date.toISOString()}`,
|
||||
content
|
||||
)
|
||||
})
|
||||
|
||||
it('should remove the file from the original bucket', async function () {
|
||||
await TestHelper.expectPersistorNotToHaveFile(
|
||||
app.persistor,
|
||||
Settings.filestore.stores.user_files,
|
||||
`${projectId}/${fileId}`
|
||||
)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
if (BackendSettings[backend].fallback) {
|
||||
describe('with a fallback', function () {
|
||||
let constantFileContent,
|
||||
fileId,
|
||||
fileKey,
|
||||
fileUrl,
|
||||
bucket,
|
||||
fallbackBucket
|
||||
|
||||
beforeEach(function () {
|
||||
constantFileContent = `This is yet more file content ${Math.random()}`
|
||||
fileId = ObjectId().toString()
|
||||
fileKey = `${projectId}/${fileId}`
|
||||
fileUrl = `${filestoreUrl}/project/${projectId}/file/${fileId}`
|
||||
|
||||
bucket = Settings.filestore.stores.user_files
|
||||
fallbackBucket = Settings.filestore.fallback.buckets[bucket]
|
||||
})
|
||||
|
||||
describe('with a file in the fallback bucket', function () {
|
||||
beforeEach(async function () {
|
||||
await TestHelper.uploadStringToPersistor(
|
||||
app.persistor.fallbackPersistor,
|
||||
fallbackBucket,
|
||||
fileKey,
|
||||
constantFileContent
|
||||
)
|
||||
})
|
||||
|
||||
it('should not find file in the primary', async function () {
|
||||
await TestHelper.expectPersistorNotToHaveFile(
|
||||
app.persistor.primaryPersistor,
|
||||
bucket,
|
||||
fileKey
|
||||
)
|
||||
})
|
||||
|
||||
it('should find the file in the fallback', async function () {
|
||||
await TestHelper.expectPersistorToHaveFile(
|
||||
app.persistor.fallbackPersistor,
|
||||
fallbackBucket,
|
||||
fileKey,
|
||||
constantFileContent
|
||||
)
|
||||
})
|
||||
|
||||
describe('when copyOnMiss is disabled', function () {
|
||||
beforeEach(function () {
|
||||
app.persistor.settings.copyOnMiss = false
|
||||
})
|
||||
|
||||
it('should fetch the file', async function () {
|
||||
const res = await rp.get(fileUrl)
|
||||
expect(res.body).to.equal(constantFileContent)
|
||||
})
|
||||
|
||||
it('should not copy the file to the primary', async function () {
|
||||
await rp.get(fileUrl)
|
||||
|
||||
await TestHelper.expectPersistorNotToHaveFile(
|
||||
app.persistor.primaryPersistor,
|
||||
bucket,
|
||||
fileKey
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
describe('when copyOnMiss is enabled', function () {
|
||||
beforeEach(function () {
|
||||
app.persistor.settings.copyOnMiss = true
|
||||
})
|
||||
|
||||
it('should fetch the file', async function () {
|
||||
const res = await rp.get(fileUrl)
|
||||
expect(res.body).to.equal(constantFileContent)
|
||||
})
|
||||
|
||||
it('copies the file to the primary', async function () {
|
||||
await rp.get(fileUrl)
|
||||
// wait for the file to copy in the background
|
||||
await msleep(1000)
|
||||
|
||||
await TestHelper.expectPersistorToHaveFile(
|
||||
app.persistor.primaryPersistor,
|
||||
bucket,
|
||||
fileKey,
|
||||
constantFileContent
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
describe('when copying a file', function () {
|
||||
let newFileId, newFileUrl, newFileKey, opts
|
||||
|
||||
beforeEach(function () {
|
||||
const newProjectID = ObjectId().toString()
|
||||
newFileId = ObjectId().toString()
|
||||
newFileUrl = `${filestoreUrl}/project/${newProjectID}/file/${newFileId}`
|
||||
newFileKey = `${newProjectID}/${newFileId}`
|
||||
|
||||
opts = {
|
||||
method: 'put',
|
||||
uri: newFileUrl,
|
||||
json: {
|
||||
source: {
|
||||
project_id: projectId,
|
||||
file_id: fileId,
|
||||
},
|
||||
},
|
||||
}
|
||||
})
|
||||
|
||||
describe('when copyOnMiss is false', function () {
|
||||
beforeEach(async function () {
|
||||
app.persistor.settings.copyOnMiss = false
|
||||
|
||||
const response = await rp(opts)
|
||||
expect(response.statusCode).to.equal(200)
|
||||
})
|
||||
|
||||
it('should leave the old file in the old bucket', async function () {
|
||||
await TestHelper.expectPersistorToHaveFile(
|
||||
app.persistor.fallbackPersistor,
|
||||
fallbackBucket,
|
||||
fileKey,
|
||||
constantFileContent
|
||||
)
|
||||
})
|
||||
|
||||
it('should not create a new file in the old bucket', async function () {
|
||||
await TestHelper.expectPersistorNotToHaveFile(
|
||||
app.persistor.fallbackPersistor,
|
||||
fallbackBucket,
|
||||
newFileKey
|
||||
)
|
||||
})
|
||||
|
||||
it('should create a new file in the new bucket', async function () {
|
||||
await TestHelper.expectPersistorToHaveFile(
|
||||
app.persistor.primaryPersistor,
|
||||
bucket,
|
||||
newFileKey,
|
||||
constantFileContent
|
||||
)
|
||||
})
|
||||
|
||||
it('should not copy the old file to the primary with the old key', async function () {
|
||||
// wait for the file to copy in the background
|
||||
await msleep(1000)
|
||||
|
||||
await TestHelper.expectPersistorNotToHaveFile(
|
||||
app.persistor.primaryPersistor,
|
||||
bucket,
|
||||
fileKey
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
describe('when copyOnMiss is true', function () {
|
||||
beforeEach(async function () {
|
||||
app.persistor.settings.copyOnMiss = true
|
||||
|
||||
const response = await rp(opts)
|
||||
expect(response.statusCode).to.equal(200)
|
||||
})
|
||||
|
||||
it('should leave the old file in the old bucket', async function () {
|
||||
await TestHelper.expectPersistorToHaveFile(
|
||||
app.persistor.fallbackPersistor,
|
||||
fallbackBucket,
|
||||
fileKey,
|
||||
constantFileContent
|
||||
)
|
||||
})
|
||||
|
||||
it('should not create a new file in the old bucket', async function () {
|
||||
await TestHelper.expectPersistorNotToHaveFile(
|
||||
app.persistor.fallbackPersistor,
|
||||
fallbackBucket,
|
||||
newFileKey
|
||||
)
|
||||
})
|
||||
|
||||
it('should create a new file in the new bucket', async function () {
|
||||
await TestHelper.expectPersistorToHaveFile(
|
||||
app.persistor.primaryPersistor,
|
||||
bucket,
|
||||
newFileKey,
|
||||
constantFileContent
|
||||
)
|
||||
})
|
||||
|
||||
it('should copy the old file to the primary with the old key', async function () {
|
||||
// wait for the file to copy in the background
|
||||
await msleep(1000)
|
||||
|
||||
await TestHelper.expectPersistorToHaveFile(
|
||||
app.persistor.primaryPersistor,
|
||||
bucket,
|
||||
fileKey,
|
||||
constantFileContent
|
||||
)
|
||||
})
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('when sending a file', function () {
|
||||
beforeEach(async function () {
|
||||
const writeStream = request.post(fileUrl)
|
||||
const readStream =
|
||||
streamifier.createReadStream(constantFileContent)
|
||||
// hack to consume the result to ensure the http request has been fully processed
|
||||
const resultStream = fs.createWriteStream('/dev/null')
|
||||
await pipeline(readStream, writeStream, resultStream)
|
||||
})
|
||||
|
||||
it('should store the file on the primary', async function () {
|
||||
await TestHelper.expectPersistorToHaveFile(
|
||||
app.persistor.primaryPersistor,
|
||||
bucket,
|
||||
fileKey,
|
||||
constantFileContent
|
||||
)
|
||||
})
|
||||
|
||||
it('should not store the file on the fallback', async function () {
|
||||
await TestHelper.expectPersistorNotToHaveFile(
|
||||
app.persistor.fallbackPersistor,
|
||||
fallbackBucket,
|
||||
`${projectId}/${fileId}`
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
describe('when deleting a file', function () {
|
||||
describe('when the file exists on the primary', function () {
|
||||
beforeEach(async function () {
|
||||
await TestHelper.uploadStringToPersistor(
|
||||
app.persistor.primaryPersistor,
|
||||
bucket,
|
||||
fileKey,
|
||||
constantFileContent
|
||||
)
|
||||
})
|
||||
|
||||
it('should delete the file', async function () {
|
||||
const response = await rp.del(fileUrl)
|
||||
expect(response.statusCode).to.equal(204)
|
||||
await expect(
|
||||
rp.get(fileUrl)
|
||||
).to.eventually.be.rejected.and.have.property('statusCode', 404)
|
||||
})
|
||||
})
|
||||
|
||||
describe('when the file exists on the fallback', function () {
|
||||
beforeEach(async function () {
|
||||
await TestHelper.uploadStringToPersistor(
|
||||
app.persistor.fallbackPersistor,
|
||||
fallbackBucket,
|
||||
fileKey,
|
||||
constantFileContent
|
||||
)
|
||||
})
|
||||
|
||||
it('should delete the file', async function () {
|
||||
const response = await rp.del(fileUrl)
|
||||
expect(response.statusCode).to.equal(204)
|
||||
await expect(
|
||||
rp.get(fileUrl)
|
||||
).to.eventually.be.rejected.and.have.property('statusCode', 404)
|
||||
})
|
||||
})
|
||||
|
||||
describe('when the file exists on both the primary and the fallback', function () {
|
||||
beforeEach(async function () {
|
||||
await TestHelper.uploadStringToPersistor(
|
||||
app.persistor.primaryPersistor,
|
||||
bucket,
|
||||
fileKey,
|
||||
constantFileContent
|
||||
)
|
||||
await TestHelper.uploadStringToPersistor(
|
||||
app.persistor.fallbackPersistor,
|
||||
fallbackBucket,
|
||||
fileKey,
|
||||
constantFileContent
|
||||
)
|
||||
})
|
||||
|
||||
it('should delete the files', async function () {
|
||||
const response = await rp.del(fileUrl)
|
||||
expect(response.statusCode).to.equal(204)
|
||||
await expect(
|
||||
rp.get(fileUrl)
|
||||
).to.eventually.be.rejected.and.have.property('statusCode', 404)
|
||||
})
|
||||
})
|
||||
|
||||
describe('when the file does not exist', function () {
|
||||
it('should return return 204', async function () {
|
||||
// S3 doesn't give us a 404 when the object doesn't exist, so to stay
|
||||
// consistent we merrily return 204 ourselves here as well
|
||||
const response = await rp.del(fileUrl)
|
||||
expect(response.statusCode).to.equal(204)
|
||||
})
|
||||
})
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
describe('with a pdf file', function () {
|
||||
let fileId, fileUrl, localFileSize
|
||||
const localFileReadPath = Path.resolve(
|
||||
__dirname,
|
||||
'../../fixtures/test.pdf'
|
||||
)
|
||||
|
||||
beforeEach(async function () {
|
||||
fileId = ObjectId().toString()
|
||||
fileUrl = `${filestoreUrl}/project/${projectId}/file/${fileId}`
|
||||
const stat = await fsStat(localFileReadPath)
|
||||
localFileSize = stat.size
|
||||
const writeStream = request.post(fileUrl)
|
||||
const endStream = fs.createWriteStream('/dev/null')
|
||||
const readStream = fs.createReadStream(localFileReadPath)
|
||||
await pipeline(readStream, writeStream, endStream)
|
||||
})
|
||||
|
||||
it('should be able get the file back', async function () {
|
||||
const response = await rp.get(fileUrl)
|
||||
expect(response.body.substring(0, 8)).to.equal('%PDF-1.5')
|
||||
})
|
||||
|
||||
if (['S3Persistor', 'GcsPersistor'].includes(backend)) {
|
||||
it('should record an egress metric for the upload', async function () {
|
||||
const metric = await TestHelper.getMetric(
|
||||
filestoreUrl,
|
||||
`${metricPrefix}_egress`
|
||||
)
|
||||
expect(metric - previousEgress).to.equal(localFileSize)
|
||||
})
|
||||
}
|
||||
|
||||
describe('getting the preview image', function () {
|
||||
this.timeout(1000 * 20)
|
||||
let previewFileUrl
|
||||
|
||||
beforeEach(function () {
|
||||
previewFileUrl = `${fileUrl}?style=preview`
|
||||
})
|
||||
|
||||
it('should not time out', async function () {
|
||||
const response = await rp.get(previewFileUrl)
|
||||
expect(response.statusCode).to.equal(200)
|
||||
})
|
||||
|
||||
it('should respond with image data', async function () {
|
||||
// note: this test relies of the imagemagick conversion working
|
||||
const response = await rp.get(previewFileUrl)
|
||||
expect(response.body.length).to.be.greaterThan(400)
|
||||
expect(response.body.substr(1, 3)).to.equal('PNG')
|
||||
})
|
||||
})
|
||||
|
||||
describe('warming the cache', function () {
|
||||
this.timeout(1000 * 20)
|
||||
let previewFileUrl
|
||||
|
||||
beforeEach(function () {
|
||||
previewFileUrl = `${fileUrl}?style=preview&cacheWarm=true`
|
||||
})
|
||||
|
||||
it('should not time out', async function () {
|
||||
const response = await rp.get(previewFileUrl)
|
||||
expect(response.statusCode).to.equal(200)
|
||||
})
|
||||
|
||||
it("should respond with only an 'OK'", async function () {
|
||||
// note: this test relies of the imagemagick conversion working
|
||||
const response = await rp.get(previewFileUrl)
|
||||
expect(response.body).to.equal('OK')
|
||||
})
|
||||
})
|
||||
})
|
||||
})
|
||||
})
|
||||
})
|
113
services/filestore/test/acceptance/js/TestConfig.js
Normal file
113
services/filestore/test/acceptance/js/TestConfig.js
Normal file
|
@ -0,0 +1,113 @@
|
|||
const Path = require('path')
|
||||
|
||||
// use functions to get a fresh copy, not a reference, each time
|
||||
function s3Config() {
|
||||
return {
|
||||
key: process.env.AWS_ACCESS_KEY_ID,
|
||||
secret: process.env.AWS_SECRET_ACCESS_KEY,
|
||||
endpoint: process.env.AWS_S3_ENDPOINT,
|
||||
pathStyle: true,
|
||||
partSize: 100 * 1024 * 1024,
|
||||
}
|
||||
}
|
||||
|
||||
function s3Stores() {
|
||||
return {
|
||||
user_files: process.env.AWS_S3_USER_FILES_BUCKET_NAME,
|
||||
template_files: process.env.AWS_S3_TEMPLATE_FILES_BUCKET_NAME,
|
||||
public_files: process.env.AWS_S3_PUBLIC_FILES_BUCKET_NAME,
|
||||
}
|
||||
}
|
||||
|
||||
function gcsConfig() {
|
||||
return {
|
||||
endpoint: {
|
||||
apiEndpoint: process.env.GCS_API_ENDPOINT,
|
||||
apiScheme: process.env.GCS_API_SCHEME,
|
||||
projectId: 'fake',
|
||||
},
|
||||
directoryKeyRegex: new RegExp('^[0-9a-fA-F]{24}/[0-9a-fA-F]{24}'),
|
||||
unlockBeforeDelete: false, // fake-gcs does not support this
|
||||
deletedBucketSuffix: '-deleted',
|
||||
}
|
||||
}
|
||||
|
||||
function gcsStores() {
|
||||
return {
|
||||
user_files: process.env.GCS_USER_FILES_BUCKET_NAME,
|
||||
template_files: process.env.GCS_TEMPLATE_FILES_BUCKET_NAME,
|
||||
public_files: process.env.GCS_PUBLIC_FILES_BUCKET_NAME,
|
||||
}
|
||||
}
|
||||
|
||||
function fsStores() {
|
||||
return {
|
||||
user_files: Path.resolve(__dirname, '../../../user_files'),
|
||||
public_files: Path.resolve(__dirname, '../../../public_files'),
|
||||
template_files: Path.resolve(__dirname, '../../../template_files'),
|
||||
}
|
||||
}
|
||||
|
||||
function fallbackStores(primaryConfig, fallbackConfig) {
|
||||
return {
|
||||
[primaryConfig.user_files]: fallbackConfig.user_files,
|
||||
[primaryConfig.public_files]: fallbackConfig.public_files,
|
||||
[primaryConfig.template_files]: fallbackConfig.template_files,
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
FSPersistor: {
|
||||
backend: 'fs',
|
||||
stores: fsStores(),
|
||||
},
|
||||
S3Persistor: {
|
||||
backend: 's3',
|
||||
s3: s3Config(),
|
||||
stores: s3Stores(),
|
||||
},
|
||||
GcsPersistor: {
|
||||
backend: 'gcs',
|
||||
gcs: gcsConfig(),
|
||||
stores: gcsStores(),
|
||||
},
|
||||
FallbackS3ToFSPersistor: {
|
||||
backend: 's3',
|
||||
s3: s3Config(),
|
||||
stores: s3Stores(),
|
||||
fallback: {
|
||||
backend: 'fs',
|
||||
buckets: fallbackStores(s3Stores(), fsStores()),
|
||||
},
|
||||
},
|
||||
FallbackFSToS3Persistor: {
|
||||
backend: 'fs',
|
||||
s3: s3Config(),
|
||||
stores: fsStores(),
|
||||
fallback: {
|
||||
backend: 's3',
|
||||
buckets: fallbackStores(fsStores(), s3Stores()),
|
||||
},
|
||||
},
|
||||
FallbackGcsToS3Persistor: {
|
||||
backend: 'gcs',
|
||||
gcs: gcsConfig(),
|
||||
stores: gcsStores(),
|
||||
s3: s3Config(),
|
||||
fallback: {
|
||||
backend: 's3',
|
||||
buckets: fallbackStores(gcsStores(), s3Stores()),
|
||||
},
|
||||
},
|
||||
FallbackS3ToGcsPersistor: {
|
||||
backend: 's3',
|
||||
// can use the same bucket names for gcs and s3 (in tests)
|
||||
stores: s3Stores(),
|
||||
s3: s3Config(),
|
||||
gcs: gcsConfig(),
|
||||
fallback: {
|
||||
backend: 'gcs',
|
||||
buckets: fallbackStores(s3Stores(), gcsStores()),
|
||||
},
|
||||
},
|
||||
}
|
54
services/filestore/test/acceptance/js/TestHelper.js
Normal file
54
services/filestore/test/acceptance/js/TestHelper.js
Normal file
|
@ -0,0 +1,54 @@
|
|||
const streamifier = require('streamifier')
|
||||
const rp = require('request-promise-native').defaults({
|
||||
resolveWithFullResponse: true,
|
||||
})
|
||||
|
||||
const { expect } = require('chai')
|
||||
|
||||
module.exports = {
|
||||
uploadStringToPersistor,
|
||||
getStringFromPersistor,
|
||||
expectPersistorToHaveFile,
|
||||
expectPersistorNotToHaveFile,
|
||||
streamToString,
|
||||
getMetric,
|
||||
}
|
||||
|
||||
async function getMetric(filestoreUrl, metric) {
|
||||
const res = await rp.get(`${filestoreUrl}/metrics`)
|
||||
expect(res.statusCode).to.equal(200)
|
||||
const metricRegex = new RegExp(`^${metric}{[^}]+} ([0-9]+)$`, 'm')
|
||||
const found = metricRegex.exec(res.body)
|
||||
return parseInt(found ? found[1] : 0) || 0
|
||||
}
|
||||
|
||||
function streamToString(stream) {
|
||||
const chunks = []
|
||||
return new Promise((resolve, reject) => {
|
||||
stream.on('data', chunk => chunks.push(chunk))
|
||||
stream.on('error', reject)
|
||||
stream.on('end', () => resolve(Buffer.concat(chunks).toString('utf8')))
|
||||
stream.resume()
|
||||
})
|
||||
}
|
||||
|
||||
async function uploadStringToPersistor(persistor, bucket, key, content) {
|
||||
const fileStream = streamifier.createReadStream(content)
|
||||
await persistor.sendStream(bucket, key, fileStream)
|
||||
}
|
||||
|
||||
async function getStringFromPersistor(persistor, bucket, key) {
|
||||
const stream = await persistor.getObjectStream(bucket, key, {})
|
||||
return streamToString(stream)
|
||||
}
|
||||
|
||||
async function expectPersistorToHaveFile(persistor, bucket, key, content) {
|
||||
const foundContent = await getStringFromPersistor(persistor, bucket, key)
|
||||
expect(foundContent).to.equal(content)
|
||||
}
|
||||
|
||||
async function expectPersistorNotToHaveFile(persistor, bucket, key) {
|
||||
await expect(
|
||||
getStringFromPersistor(persistor, bucket, key)
|
||||
).to.eventually.have.been.rejected.with.property('name', 'NotFoundError')
|
||||
}
|
BIN
services/filestore/test/fixtures/test.pdf
vendored
Normal file
BIN
services/filestore/test/fixtures/test.pdf
vendored
Normal file
Binary file not shown.
347
services/filestore/test/unit/js/FileControllerTests.js
Normal file
347
services/filestore/test/unit/js/FileControllerTests.js
Normal file
|
@ -0,0 +1,347 @@
|
|||
const sinon = require('sinon')
|
||||
const chai = require('chai')
|
||||
const { expect } = chai
|
||||
const SandboxedModule = require('sandboxed-module')
|
||||
const Errors = require('../../../app/js/Errors')
|
||||
const modulePath = '../../../app/js/FileController.js'
|
||||
|
||||
describe('FileController', function () {
|
||||
let PersistorManager,
|
||||
FileHandler,
|
||||
LocalFileWriter,
|
||||
FileController,
|
||||
req,
|
||||
res,
|
||||
next,
|
||||
stream
|
||||
const settings = {
|
||||
s3: {
|
||||
buckets: {
|
||||
user_files: 'user_files',
|
||||
},
|
||||
},
|
||||
}
|
||||
const fileSize = 1234
|
||||
const fileStream = 'fileStream'
|
||||
const projectId = 'projectId'
|
||||
const fileId = 'file_id'
|
||||
const bucket = 'user_files'
|
||||
const key = `${projectId}/${fileId}`
|
||||
const error = new Error('incorrect utensil')
|
||||
|
||||
beforeEach(function () {
|
||||
PersistorManager = {
|
||||
sendStream: sinon.stub().yields(),
|
||||
copyObject: sinon.stub().resolves(),
|
||||
deleteObject: sinon.stub().yields(),
|
||||
}
|
||||
|
||||
FileHandler = {
|
||||
getFile: sinon.stub().yields(null, fileStream),
|
||||
getFileSize: sinon.stub().yields(null, fileSize),
|
||||
deleteFile: sinon.stub().yields(),
|
||||
deleteProject: sinon.stub().yields(),
|
||||
insertFile: sinon.stub().yields(),
|
||||
getDirectorySize: sinon.stub().yields(null, fileSize),
|
||||
getRedirectUrl: sinon.stub().yields(null, null),
|
||||
}
|
||||
|
||||
LocalFileWriter = {}
|
||||
stream = {
|
||||
pipeline: sinon.stub(),
|
||||
}
|
||||
|
||||
FileController = SandboxedModule.require(modulePath, {
|
||||
requires: {
|
||||
'./LocalFileWriter': LocalFileWriter,
|
||||
'./FileHandler': FileHandler,
|
||||
'./PersistorManager': PersistorManager,
|
||||
'./Errors': Errors,
|
||||
stream: stream,
|
||||
'@overleaf/settings': settings,
|
||||
'@overleaf/metrics': {
|
||||
inc() {},
|
||||
},
|
||||
},
|
||||
globals: { console },
|
||||
})
|
||||
|
||||
req = {
|
||||
key: key,
|
||||
bucket: bucket,
|
||||
project_id: projectId,
|
||||
query: {},
|
||||
params: {
|
||||
project_id: projectId,
|
||||
file_id: fileId,
|
||||
},
|
||||
headers: {},
|
||||
requestLogger: {
|
||||
setMessage: sinon.stub(),
|
||||
addFields: sinon.stub(),
|
||||
},
|
||||
}
|
||||
|
||||
res = {
|
||||
set: sinon.stub().returnsThis(),
|
||||
sendStatus: sinon.stub().returnsThis(),
|
||||
status: sinon.stub().returnsThis(),
|
||||
}
|
||||
|
||||
next = sinon.stub()
|
||||
})
|
||||
|
||||
describe('getFile', function () {
|
||||
it('should try and get a redirect url first', function () {
|
||||
FileController.getFile(req, res, next)
|
||||
expect(FileHandler.getRedirectUrl).to.have.been.calledWith(bucket, key)
|
||||
})
|
||||
|
||||
it('should pipe the stream', function () {
|
||||
FileController.getFile(req, res, next)
|
||||
expect(stream.pipeline).to.have.been.calledWith(fileStream, res)
|
||||
})
|
||||
|
||||
it('should send a 200 if the cacheWarm param is true', function (done) {
|
||||
req.query.cacheWarm = true
|
||||
res.sendStatus = statusCode => {
|
||||
statusCode.should.equal(200)
|
||||
done()
|
||||
}
|
||||
FileController.getFile(req, res, next)
|
||||
})
|
||||
|
||||
it('should send an error if there is a problem', function () {
|
||||
FileHandler.getFile.yields(error)
|
||||
FileController.getFile(req, res, next)
|
||||
expect(next).to.have.been.calledWith(error)
|
||||
})
|
||||
|
||||
describe('with a redirect url', function () {
|
||||
const redirectUrl = 'https://wombat.potato/giraffe'
|
||||
|
||||
beforeEach(function () {
|
||||
FileHandler.getRedirectUrl.yields(null, redirectUrl)
|
||||
res.redirect = sinon.stub()
|
||||
})
|
||||
|
||||
it('should redirect', function () {
|
||||
FileController.getFile(req, res, next)
|
||||
expect(res.redirect).to.have.been.calledWith(redirectUrl)
|
||||
})
|
||||
|
||||
it('should not get a file stream', function () {
|
||||
FileController.getFile(req, res, next)
|
||||
expect(FileHandler.getFile).not.to.have.been.called
|
||||
})
|
||||
|
||||
describe('when there is an error getting the redirect url', function () {
|
||||
beforeEach(function () {
|
||||
FileHandler.getRedirectUrl.yields(new Error('wombat herding error'))
|
||||
})
|
||||
|
||||
it('should not redirect', function () {
|
||||
FileController.getFile(req, res, next)
|
||||
expect(res.redirect).not.to.have.been.called
|
||||
})
|
||||
|
||||
it('should not return an error', function () {
|
||||
FileController.getFile(req, res, next)
|
||||
expect(next).not.to.have.been.called
|
||||
})
|
||||
|
||||
it('should proxy the file', function () {
|
||||
FileController.getFile(req, res, next)
|
||||
expect(FileHandler.getFile).to.have.been.calledWith(bucket, key)
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('with a range header', function () {
|
||||
let expectedOptions
|
||||
|
||||
beforeEach(function () {
|
||||
expectedOptions = {
|
||||
bucket,
|
||||
key,
|
||||
format: undefined,
|
||||
style: undefined,
|
||||
}
|
||||
})
|
||||
|
||||
it('should pass range options to FileHandler', function () {
|
||||
req.headers.range = 'bytes=0-8'
|
||||
expectedOptions.start = 0
|
||||
expectedOptions.end = 8
|
||||
|
||||
FileController.getFile(req, res, next)
|
||||
expect(FileHandler.getFile).to.have.been.calledWith(
|
||||
bucket,
|
||||
key,
|
||||
expectedOptions
|
||||
)
|
||||
})
|
||||
|
||||
it('should ignore an invalid range header', function () {
|
||||
req.headers.range = 'potato'
|
||||
FileController.getFile(req, res, next)
|
||||
expect(FileHandler.getFile).to.have.been.calledWith(
|
||||
bucket,
|
||||
key,
|
||||
expectedOptions
|
||||
)
|
||||
})
|
||||
|
||||
it("should ignore any type other than 'bytes'", function () {
|
||||
req.headers.range = 'wombats=0-8'
|
||||
FileController.getFile(req, res, next)
|
||||
expect(FileHandler.getFile).to.have.been.calledWith(
|
||||
bucket,
|
||||
key,
|
||||
expectedOptions
|
||||
)
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('getFileHead', function () {
|
||||
it('should return the file size in a Content-Length header', function (done) {
|
||||
res.end = () => {
|
||||
expect(res.status).to.have.been.calledWith(200)
|
||||
expect(res.set).to.have.been.calledWith('Content-Length', fileSize)
|
||||
done()
|
||||
}
|
||||
|
||||
FileController.getFileHead(req, res, next)
|
||||
})
|
||||
|
||||
it('should return a 404 is the file is not found', function (done) {
|
||||
FileHandler.getFileSize.yields(
|
||||
new Errors.NotFoundError({ message: 'not found', info: {} })
|
||||
)
|
||||
|
||||
res.sendStatus = code => {
|
||||
expect(code).to.equal(404)
|
||||
done()
|
||||
}
|
||||
|
||||
FileController.getFileHead(req, res, next)
|
||||
})
|
||||
|
||||
it('should send an error on internal errors', function () {
|
||||
FileHandler.getFileSize.yields(error)
|
||||
|
||||
FileController.getFileHead(req, res, next)
|
||||
expect(next).to.have.been.calledWith(error)
|
||||
})
|
||||
})
|
||||
|
||||
describe('insertFile', function () {
|
||||
it('should send bucket name key and res to PersistorManager', function (done) {
|
||||
res.sendStatus = code => {
|
||||
expect(FileHandler.insertFile).to.have.been.calledWith(bucket, key, req)
|
||||
expect(code).to.equal(200)
|
||||
done()
|
||||
}
|
||||
FileController.insertFile(req, res, next)
|
||||
})
|
||||
})
|
||||
|
||||
describe('copyFile', function () {
|
||||
const oldFileId = 'oldFileId'
|
||||
const oldProjectId = 'oldProjectid'
|
||||
const oldKey = `${oldProjectId}/${oldFileId}`
|
||||
|
||||
beforeEach(function () {
|
||||
req.body = {
|
||||
source: {
|
||||
project_id: oldProjectId,
|
||||
file_id: oldFileId,
|
||||
},
|
||||
}
|
||||
})
|
||||
|
||||
it('should send bucket name and both keys to PersistorManager', function (done) {
|
||||
res.sendStatus = code => {
|
||||
code.should.equal(200)
|
||||
expect(PersistorManager.copyObject).to.have.been.calledWith(
|
||||
bucket,
|
||||
oldKey,
|
||||
key
|
||||
)
|
||||
done()
|
||||
}
|
||||
FileController.copyFile(req, res, next)
|
||||
})
|
||||
|
||||
it('should send a 404 if the original file was not found', function (done) {
|
||||
PersistorManager.copyObject.rejects(
|
||||
new Errors.NotFoundError({ message: 'not found', info: {} })
|
||||
)
|
||||
res.sendStatus = code => {
|
||||
code.should.equal(404)
|
||||
done()
|
||||
}
|
||||
FileController.copyFile(req, res, next)
|
||||
})
|
||||
|
||||
it('should send an error if there was an error', function (done) {
|
||||
PersistorManager.copyObject.rejects(error)
|
||||
FileController.copyFile(req, res, err => {
|
||||
expect(err).to.equal(error)
|
||||
done()
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('delete file', function () {
|
||||
it('should tell the file handler', function (done) {
|
||||
res.sendStatus = code => {
|
||||
code.should.equal(204)
|
||||
expect(FileHandler.deleteFile).to.have.been.calledWith(bucket, key)
|
||||
done()
|
||||
}
|
||||
FileController.deleteFile(req, res, next)
|
||||
})
|
||||
|
||||
it('should send a 500 if there was an error', function () {
|
||||
FileHandler.deleteFile.yields(error)
|
||||
FileController.deleteFile(req, res, next)
|
||||
expect(next).to.have.been.calledWith(error)
|
||||
})
|
||||
})
|
||||
|
||||
describe('delete project', function () {
|
||||
it('should tell the file handler', function (done) {
|
||||
res.sendStatus = code => {
|
||||
code.should.equal(204)
|
||||
expect(FileHandler.deleteProject).to.have.been.calledWith(bucket, key)
|
||||
done()
|
||||
}
|
||||
FileController.deleteProject(req, res, next)
|
||||
})
|
||||
|
||||
it('should send a 500 if there was an error', function () {
|
||||
FileHandler.deleteProject.yields(error)
|
||||
FileController.deleteProject(req, res, next)
|
||||
expect(next).to.have.been.calledWith(error)
|
||||
})
|
||||
})
|
||||
|
||||
describe('directorySize', function () {
|
||||
it('should return total directory size bytes', function (done) {
|
||||
FileController.directorySize(req, {
|
||||
json: result => {
|
||||
expect(result['total bytes']).to.equal(fileSize)
|
||||
done()
|
||||
},
|
||||
})
|
||||
})
|
||||
|
||||
it('should send a 500 if there was an error', function () {
|
||||
FileHandler.getDirectorySize.yields(error)
|
||||
FileController.directorySize(req, res, next)
|
||||
expect(next).to.have.been.calledWith(error)
|
||||
})
|
||||
})
|
||||
})
|
107
services/filestore/test/unit/js/FileConverterTests.js
Normal file
107
services/filestore/test/unit/js/FileConverterTests.js
Normal file
|
@ -0,0 +1,107 @@
|
|||
const sinon = require('sinon')
|
||||
const chai = require('chai')
|
||||
const { expect } = chai
|
||||
const SandboxedModule = require('sandboxed-module')
|
||||
const { Errors } = require('@overleaf/object-persistor')
|
||||
|
||||
const modulePath = '../../../app/js/FileConverter.js'
|
||||
|
||||
describe('FileConverter', function () {
|
||||
let SafeExec, FileConverter
|
||||
const sourcePath = '/data/wombat.eps'
|
||||
const destPath = '/tmp/dest.png'
|
||||
const format = 'png'
|
||||
const errorMessage = 'guru meditation error'
|
||||
const Settings = {
|
||||
commands: {
|
||||
convertCommandPrefix: [],
|
||||
},
|
||||
}
|
||||
|
||||
beforeEach(function () {
|
||||
SafeExec = {
|
||||
promises: sinon.stub().resolves(destPath),
|
||||
}
|
||||
|
||||
const ObjectPersistor = { Errors }
|
||||
|
||||
FileConverter = SandboxedModule.require(modulePath, {
|
||||
requires: {
|
||||
'./SafeExec': SafeExec,
|
||||
'@overleaf/metrics': {
|
||||
inc: sinon.stub(),
|
||||
Timer: sinon.stub().returns({ done: sinon.stub() }),
|
||||
},
|
||||
'@overleaf/settings': Settings,
|
||||
'@overleaf/object-persistor': ObjectPersistor,
|
||||
},
|
||||
})
|
||||
})
|
||||
|
||||
describe('convert', function () {
|
||||
it('should convert the source to the requested format', async function () {
|
||||
await FileConverter.promises.convert(sourcePath, format)
|
||||
const args = SafeExec.promises.args[0][0]
|
||||
expect(args).to.include(`${sourcePath}[0]`)
|
||||
expect(args).to.include(`${sourcePath}.${format}`)
|
||||
})
|
||||
|
||||
it('should return the dest path', async function () {
|
||||
const destPath = await FileConverter.promises.convert(sourcePath, format)
|
||||
destPath.should.equal(`${sourcePath}.${format}`)
|
||||
})
|
||||
|
||||
it('should wrap the error from convert', async function () {
|
||||
SafeExec.promises.rejects(errorMessage)
|
||||
try {
|
||||
await FileConverter.promises.convert(sourcePath, format)
|
||||
expect('error should have been thrown').not.to.exist
|
||||
} catch (err) {
|
||||
expect(err.name).to.equal('ConversionError')
|
||||
expect(err.cause.toString()).to.equal(errorMessage)
|
||||
}
|
||||
})
|
||||
|
||||
it('should not accept an non approved format', async function () {
|
||||
try {
|
||||
await FileConverter.promises.convert(sourcePath, 'potato')
|
||||
expect('error should have been thrown').not.to.exist
|
||||
} catch (err) {
|
||||
expect(err.name).to.equal('ConversionError')
|
||||
}
|
||||
})
|
||||
|
||||
it('should prefix the command with Settings.commands.convertCommandPrefix', async function () {
|
||||
Settings.commands.convertCommandPrefix = ['nice']
|
||||
await FileConverter.promises.convert(sourcePath, format)
|
||||
})
|
||||
|
||||
it('should convert the file when called as a callback', function (done) {
|
||||
FileConverter.convert(sourcePath, format, (err, destPath) => {
|
||||
expect(err).not.to.exist
|
||||
destPath.should.equal(`${sourcePath}.${format}`)
|
||||
|
||||
const args = SafeExec.promises.args[0][0]
|
||||
expect(args).to.include(`${sourcePath}[0]`)
|
||||
expect(args).to.include(`${sourcePath}.${format}`)
|
||||
done()
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('thumbnail', function () {
|
||||
it('should call converter resize with args', async function () {
|
||||
await FileConverter.promises.thumbnail(sourcePath)
|
||||
const args = SafeExec.promises.args[0][0]
|
||||
expect(args).to.include(`${sourcePath}[0]`)
|
||||
})
|
||||
})
|
||||
|
||||
describe('preview', function () {
|
||||
it('should call converter resize with args', async function () {
|
||||
await FileConverter.promises.preview(sourcePath)
|
||||
const args = SafeExec.promises.args[0][0]
|
||||
expect(args).to.include(`${sourcePath}[0]`)
|
||||
})
|
||||
})
|
||||
})
|
398
services/filestore/test/unit/js/FileHandlerTests.js
Normal file
398
services/filestore/test/unit/js/FileHandlerTests.js
Normal file
|
@ -0,0 +1,398 @@
|
|||
const sinon = require('sinon')
|
||||
const chai = require('chai')
|
||||
const { expect } = chai
|
||||
const modulePath = '../../../app/js/FileHandler.js'
|
||||
const SandboxedModule = require('sandboxed-module')
|
||||
const { ObjectId } = require('mongodb')
|
||||
const { Errors } = require('@overleaf/object-persistor')
|
||||
|
||||
chai.use(require('sinon-chai'))
|
||||
chai.use(require('chai-as-promised'))
|
||||
|
||||
describe('FileHandler', function () {
|
||||
let PersistorManager,
|
||||
LocalFileWriter,
|
||||
FileConverter,
|
||||
KeyBuilder,
|
||||
ImageOptimiser,
|
||||
FileHandler,
|
||||
Settings,
|
||||
fs
|
||||
|
||||
const bucket = 'my_bucket'
|
||||
const key = `${ObjectId()}/${ObjectId()}`
|
||||
const convertedFolderKey = `${ObjectId()}/${ObjectId()}`
|
||||
const projectKey = `${ObjectId()}/`
|
||||
const sourceStream = 'sourceStream'
|
||||
const convertedKey = 'convertedKey'
|
||||
const redirectUrl = 'https://wombat.potato/giraffe'
|
||||
const readStream = {
|
||||
stream: 'readStream',
|
||||
on: sinon.stub(),
|
||||
}
|
||||
|
||||
beforeEach(function () {
|
||||
PersistorManager = {
|
||||
getObjectStream: sinon.stub().resolves(sourceStream),
|
||||
getRedirectUrl: sinon.stub().resolves(redirectUrl),
|
||||
checkIfObjectExists: sinon.stub().resolves(),
|
||||
deleteObject: sinon.stub().resolves(),
|
||||
deleteDirectory: sinon.stub().resolves(),
|
||||
sendStream: sinon.stub().resolves(),
|
||||
insertFile: sinon.stub().resolves(),
|
||||
sendFile: sinon.stub().resolves(),
|
||||
directorySize: sinon.stub().resolves(),
|
||||
}
|
||||
LocalFileWriter = {
|
||||
// the callback style is used for detached cleanup calls
|
||||
deleteFile: sinon.stub().yields(),
|
||||
promises: {
|
||||
writeStream: sinon.stub().resolves(),
|
||||
deleteFile: sinon.stub().resolves(),
|
||||
},
|
||||
}
|
||||
FileConverter = {
|
||||
promises: {
|
||||
convert: sinon.stub().resolves(),
|
||||
thumbnail: sinon.stub().resolves(),
|
||||
preview: sinon.stub().resolves(),
|
||||
},
|
||||
}
|
||||
KeyBuilder = {
|
||||
addCachingToKey: sinon.stub().returns(convertedKey),
|
||||
getConvertedFolderKey: sinon.stub().returns(convertedFolderKey),
|
||||
}
|
||||
ImageOptimiser = {
|
||||
promises: {
|
||||
compressPng: sinon.stub().resolves(),
|
||||
},
|
||||
}
|
||||
Settings = {}
|
||||
fs = {
|
||||
createReadStream: sinon.stub().returns(readStream),
|
||||
}
|
||||
|
||||
const ObjectPersistor = { Errors }
|
||||
|
||||
FileHandler = SandboxedModule.require(modulePath, {
|
||||
requires: {
|
||||
'./PersistorManager': PersistorManager,
|
||||
'./LocalFileWriter': LocalFileWriter,
|
||||
'./FileConverter': FileConverter,
|
||||
'./KeyBuilder': KeyBuilder,
|
||||
'./ImageOptimiser': ImageOptimiser,
|
||||
'@overleaf/settings': Settings,
|
||||
'@overleaf/object-persistor': ObjectPersistor,
|
||||
fs: fs,
|
||||
},
|
||||
globals: { console },
|
||||
})
|
||||
})
|
||||
|
||||
describe('insertFile', function () {
|
||||
const stream = 'stream'
|
||||
|
||||
it('should send file to the filestore', function (done) {
|
||||
FileHandler.insertFile(bucket, key, stream, err => {
|
||||
expect(err).not.to.exist
|
||||
expect(PersistorManager.sendStream).to.have.been.calledWith(
|
||||
bucket,
|
||||
key,
|
||||
stream
|
||||
)
|
||||
done()
|
||||
})
|
||||
})
|
||||
|
||||
it('should not make a delete request for the convertedKey folder', function (done) {
|
||||
FileHandler.insertFile(bucket, key, stream, err => {
|
||||
expect(err).not.to.exist
|
||||
expect(PersistorManager.deleteDirectory).not.to.have.been.called
|
||||
done()
|
||||
})
|
||||
})
|
||||
|
||||
it('should accept templates-api key format', function (done) {
|
||||
KeyBuilder.getConvertedFolderKey.returns(
|
||||
'5ecba29f1a294e007d0bccb4/v/0/pdf'
|
||||
)
|
||||
FileHandler.insertFile(bucket, key, stream, err => {
|
||||
expect(err).not.to.exist
|
||||
done()
|
||||
})
|
||||
})
|
||||
|
||||
it('should throw an error when the key is in the wrong format', function (done) {
|
||||
KeyBuilder.getConvertedFolderKey.returns('wombat')
|
||||
FileHandler.insertFile(bucket, key, stream, err => {
|
||||
expect(err).to.exist
|
||||
done()
|
||||
})
|
||||
})
|
||||
|
||||
describe('when conversions are enabled', function () {
|
||||
beforeEach(function () {
|
||||
Settings.enableConversions = true
|
||||
})
|
||||
|
||||
it('should delete the convertedKey folder', function (done) {
|
||||
FileHandler.insertFile(bucket, key, stream, err => {
|
||||
expect(err).not.to.exist
|
||||
expect(PersistorManager.deleteDirectory).to.have.been.calledWith(
|
||||
bucket,
|
||||
convertedFolderKey
|
||||
)
|
||||
done()
|
||||
})
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('deleteFile', function () {
|
||||
it('should tell the filestore manager to delete the file', function (done) {
|
||||
FileHandler.deleteFile(bucket, key, err => {
|
||||
expect(err).not.to.exist
|
||||
expect(PersistorManager.deleteObject).to.have.been.calledWith(
|
||||
bucket,
|
||||
key
|
||||
)
|
||||
done()
|
||||
})
|
||||
})
|
||||
|
||||
it('should not tell the filestore manager to delete the cached folder', function (done) {
|
||||
FileHandler.deleteFile(bucket, key, err => {
|
||||
expect(err).not.to.exist
|
||||
expect(PersistorManager.deleteDirectory).not.to.have.been.called
|
||||
done()
|
||||
})
|
||||
})
|
||||
|
||||
it('should accept templates-api key format', function (done) {
|
||||
KeyBuilder.getConvertedFolderKey.returns(
|
||||
'5ecba29f1a294e007d0bccb4/v/0/pdf'
|
||||
)
|
||||
FileHandler.deleteFile(bucket, key, err => {
|
||||
expect(err).not.to.exist
|
||||
done()
|
||||
})
|
||||
})
|
||||
|
||||
it('should throw an error when the key is in the wrong format', function (done) {
|
||||
KeyBuilder.getConvertedFolderKey.returns('wombat')
|
||||
FileHandler.deleteFile(bucket, key, err => {
|
||||
expect(err).to.exist
|
||||
done()
|
||||
})
|
||||
})
|
||||
|
||||
describe('when conversions are enabled', function () {
|
||||
beforeEach(function () {
|
||||
Settings.enableConversions = true
|
||||
})
|
||||
|
||||
it('should delete the convertedKey folder', function (done) {
|
||||
FileHandler.deleteFile(bucket, key, err => {
|
||||
expect(err).not.to.exist
|
||||
expect(PersistorManager.deleteDirectory).to.have.been.calledWith(
|
||||
bucket,
|
||||
convertedFolderKey
|
||||
)
|
||||
done()
|
||||
})
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('deleteProject', function () {
|
||||
it('should tell the filestore manager to delete the folder', function (done) {
|
||||
FileHandler.deleteProject(bucket, projectKey, err => {
|
||||
expect(err).not.to.exist
|
||||
expect(PersistorManager.deleteDirectory).to.have.been.calledWith(
|
||||
bucket,
|
||||
projectKey
|
||||
)
|
||||
done()
|
||||
})
|
||||
})
|
||||
|
||||
it('should throw an error when the key is in the wrong format', function (done) {
|
||||
FileHandler.deleteProject(bucket, 'wombat', err => {
|
||||
expect(err).to.exist
|
||||
done()
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('getFile', function () {
|
||||
it('should return the source stream no format or style are defined', function (done) {
|
||||
FileHandler.getFile(bucket, key, null, (err, stream) => {
|
||||
expect(err).not.to.exist
|
||||
expect(stream).to.equal(sourceStream)
|
||||
done()
|
||||
})
|
||||
})
|
||||
|
||||
it('should pass options through to PersistorManager', function (done) {
|
||||
const options = { start: 0, end: 8 }
|
||||
FileHandler.getFile(bucket, key, options, err => {
|
||||
expect(err).not.to.exist
|
||||
expect(PersistorManager.getObjectStream).to.have.been.calledWith(
|
||||
bucket,
|
||||
key,
|
||||
options
|
||||
)
|
||||
done()
|
||||
})
|
||||
})
|
||||
|
||||
describe('when a format is defined', function () {
|
||||
let result
|
||||
|
||||
describe('when the file is not cached', function () {
|
||||
beforeEach(function (done) {
|
||||
FileHandler.getFile(bucket, key, { format: 'png' }, (err, stream) => {
|
||||
result = { err, stream }
|
||||
done()
|
||||
})
|
||||
})
|
||||
|
||||
it('should convert the file', function () {
|
||||
expect(FileConverter.promises.convert).to.have.been.called
|
||||
})
|
||||
|
||||
it('should compress the converted file', function () {
|
||||
expect(ImageOptimiser.promises.compressPng).to.have.been.called
|
||||
})
|
||||
|
||||
it('should return the the converted stream', function () {
|
||||
expect(result.err).not.to.exist
|
||||
expect(result.stream).to.equal(readStream)
|
||||
expect(PersistorManager.getObjectStream).to.have.been.calledWith(
|
||||
bucket,
|
||||
key
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
describe('when the file is cached', function () {
|
||||
beforeEach(function (done) {
|
||||
PersistorManager.checkIfObjectExists = sinon.stub().resolves(true)
|
||||
FileHandler.getFile(bucket, key, { format: 'png' }, (err, stream) => {
|
||||
result = { err, stream }
|
||||
done()
|
||||
})
|
||||
})
|
||||
|
||||
it('should not convert the file', function () {
|
||||
expect(FileConverter.promises.convert).not.to.have.been.called
|
||||
})
|
||||
|
||||
it('should not compress the converted file again', function () {
|
||||
expect(ImageOptimiser.promises.compressPng).not.to.have.been.called
|
||||
})
|
||||
|
||||
it('should return the cached stream', function () {
|
||||
expect(result.err).not.to.exist
|
||||
expect(result.stream).to.equal(sourceStream)
|
||||
expect(PersistorManager.getObjectStream).to.have.been.calledWith(
|
||||
bucket,
|
||||
convertedKey
|
||||
)
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('when a style is defined', function () {
|
||||
it('generates a thumbnail when requested', function (done) {
|
||||
FileHandler.getFile(bucket, key, { style: 'thumbnail' }, err => {
|
||||
expect(err).not.to.exist
|
||||
expect(FileConverter.promises.thumbnail).to.have.been.called
|
||||
expect(FileConverter.promises.preview).not.to.have.been.called
|
||||
done()
|
||||
})
|
||||
})
|
||||
|
||||
it('generates a preview when requested', function (done) {
|
||||
FileHandler.getFile(bucket, key, { style: 'preview' }, err => {
|
||||
expect(err).not.to.exist
|
||||
expect(FileConverter.promises.thumbnail).not.to.have.been.called
|
||||
expect(FileConverter.promises.preview).to.have.been.called
|
||||
done()
|
||||
})
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('getRedirectUrl', function () {
|
||||
beforeEach(function () {
|
||||
Settings.filestore = {
|
||||
allowRedirects: true,
|
||||
stores: {
|
||||
userFiles: bucket,
|
||||
},
|
||||
}
|
||||
})
|
||||
|
||||
it('should return a redirect url', function (done) {
|
||||
FileHandler.getRedirectUrl(bucket, key, (err, url) => {
|
||||
expect(err).not.to.exist
|
||||
expect(url).to.equal(redirectUrl)
|
||||
done()
|
||||
})
|
||||
})
|
||||
|
||||
it('should call the persistor to get a redirect url', function (done) {
|
||||
FileHandler.getRedirectUrl(bucket, key, () => {
|
||||
expect(PersistorManager.getRedirectUrl).to.have.been.calledWith(
|
||||
bucket,
|
||||
key
|
||||
)
|
||||
done()
|
||||
})
|
||||
})
|
||||
|
||||
it('should return null if options are supplied', function (done) {
|
||||
FileHandler.getRedirectUrl(
|
||||
bucket,
|
||||
key,
|
||||
{ start: 100, end: 200 },
|
||||
(err, url) => {
|
||||
expect(err).not.to.exist
|
||||
expect(url).to.be.null
|
||||
done()
|
||||
}
|
||||
)
|
||||
})
|
||||
|
||||
it('should return null if the bucket is not one of the defined ones', function (done) {
|
||||
FileHandler.getRedirectUrl('a_different_bucket', key, (err, url) => {
|
||||
expect(err).not.to.exist
|
||||
expect(url).to.be.null
|
||||
done()
|
||||
})
|
||||
})
|
||||
|
||||
it('should return null if redirects are not enabled', function (done) {
|
||||
Settings.filestore.allowRedirects = false
|
||||
FileHandler.getRedirectUrl(bucket, key, (err, url) => {
|
||||
expect(err).not.to.exist
|
||||
expect(url).to.be.null
|
||||
done()
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('getDirectorySize', function () {
|
||||
it('should call the filestore manager to get directory size', function (done) {
|
||||
FileHandler.getDirectorySize(bucket, key, err => {
|
||||
expect(err).not.to.exist
|
||||
expect(PersistorManager.directorySize).to.have.been.calledWith(
|
||||
bucket,
|
||||
key
|
||||
)
|
||||
done()
|
||||
})
|
||||
})
|
||||
})
|
||||
})
|
71
services/filestore/test/unit/js/ImageOptimiserTests.js
Normal file
71
services/filestore/test/unit/js/ImageOptimiserTests.js
Normal file
|
@ -0,0 +1,71 @@
|
|||
const sinon = require('sinon')
|
||||
const chai = require('chai')
|
||||
const { expect } = chai
|
||||
const modulePath = '../../../app/js/ImageOptimiser.js'
|
||||
const { FailedCommandError } = require('../../../app/js/Errors')
|
||||
const SandboxedModule = require('sandboxed-module')
|
||||
|
||||
describe('ImageOptimiser', function () {
|
||||
let ImageOptimiser, SafeExec, logger
|
||||
const sourcePath = '/wombat/potato.eps'
|
||||
|
||||
beforeEach(function () {
|
||||
SafeExec = {
|
||||
promises: sinon.stub().resolves(),
|
||||
}
|
||||
logger = {
|
||||
warn: sinon.stub(),
|
||||
}
|
||||
ImageOptimiser = SandboxedModule.require(modulePath, {
|
||||
requires: {
|
||||
'./SafeExec': SafeExec,
|
||||
'logger-sharelatex': logger,
|
||||
'@overleaf/metrics': {
|
||||
Timer: sinon.stub().returns({ done: sinon.stub() }),
|
||||
},
|
||||
},
|
||||
})
|
||||
})
|
||||
|
||||
describe('compressPng', function () {
|
||||
it('should convert the file', function (done) {
|
||||
ImageOptimiser.compressPng(sourcePath, err => {
|
||||
expect(err).not.to.exist
|
||||
expect(SafeExec.promises).to.have.been.calledWith([
|
||||
'optipng',
|
||||
sourcePath,
|
||||
])
|
||||
done()
|
||||
})
|
||||
})
|
||||
|
||||
it('should return the error', function (done) {
|
||||
SafeExec.promises.rejects('wombat herding failure')
|
||||
ImageOptimiser.compressPng(sourcePath, err => {
|
||||
expect(err.toString()).to.equal('wombat herding failure')
|
||||
done()
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('when optimiser is sigkilled', function () {
|
||||
const expectedError = new FailedCommandError('', 'SIGKILL', '', '')
|
||||
let error
|
||||
|
||||
beforeEach(function (done) {
|
||||
SafeExec.promises.rejects(expectedError)
|
||||
ImageOptimiser.compressPng(sourcePath, err => {
|
||||
error = err
|
||||
done()
|
||||
})
|
||||
})
|
||||
|
||||
it('should not produce an error', function () {
|
||||
expect(error).not.to.exist
|
||||
})
|
||||
|
||||
it('should log a warning', function () {
|
||||
expect(logger.warn).to.have.been.calledOnce
|
||||
})
|
||||
})
|
||||
})
|
37
services/filestore/test/unit/js/KeybuilderTests.js
Normal file
37
services/filestore/test/unit/js/KeybuilderTests.js
Normal file
|
@ -0,0 +1,37 @@
|
|||
const SandboxedModule = require('sandboxed-module')
|
||||
|
||||
const modulePath = '../../../app/js/KeyBuilder.js'
|
||||
|
||||
describe('KeybuilderTests', function () {
|
||||
let KeyBuilder
|
||||
const key = 'wombat/potato'
|
||||
|
||||
beforeEach(function () {
|
||||
KeyBuilder = SandboxedModule.require(modulePath, {
|
||||
requires: { '@overleaf/settings': {} },
|
||||
})
|
||||
})
|
||||
|
||||
describe('cachedKey', function () {
|
||||
it('should add the format to the key', function () {
|
||||
const opts = { format: 'png' }
|
||||
const newKey = KeyBuilder.addCachingToKey(key, opts)
|
||||
newKey.should.equal(`${key}-converted-cache/format-png`)
|
||||
})
|
||||
|
||||
it('should add the style to the key', function () {
|
||||
const opts = { style: 'thumbnail' }
|
||||
const newKey = KeyBuilder.addCachingToKey(key, opts)
|
||||
newKey.should.equal(`${key}-converted-cache/style-thumbnail`)
|
||||
})
|
||||
|
||||
it('should add format first, then style', function () {
|
||||
const opts = {
|
||||
style: 'thumbnail',
|
||||
format: 'png',
|
||||
}
|
||||
const newKey = KeyBuilder.addCachingToKey(key, opts)
|
||||
newKey.should.equal(`${key}-converted-cache/format-png-style-thumbnail`)
|
||||
})
|
||||
})
|
||||
})
|
111
services/filestore/test/unit/js/LocalFileWriterTests.js
Normal file
111
services/filestore/test/unit/js/LocalFileWriterTests.js
Normal file
|
@ -0,0 +1,111 @@
|
|||
const sinon = require('sinon')
|
||||
const chai = require('chai')
|
||||
const { expect } = chai
|
||||
const modulePath = '../../../app/js/LocalFileWriter.js'
|
||||
const SandboxedModule = require('sandboxed-module')
|
||||
const { Errors } = require('@overleaf/object-persistor')
|
||||
chai.use(require('sinon-chai'))
|
||||
|
||||
describe('LocalFileWriter', function () {
|
||||
const writeStream = 'writeStream'
|
||||
const readStream = 'readStream'
|
||||
const settings = { path: { uploadFolder: '/uploads' } }
|
||||
const fsPath = '/uploads/wombat'
|
||||
const filename = 'wombat'
|
||||
let stream, fs, LocalFileWriter
|
||||
|
||||
beforeEach(function () {
|
||||
fs = {
|
||||
createWriteStream: sinon.stub().returns(writeStream),
|
||||
unlink: sinon.stub().yields(),
|
||||
}
|
||||
stream = {
|
||||
pipeline: sinon.stub().yields(),
|
||||
}
|
||||
|
||||
const ObjectPersistor = { Errors }
|
||||
|
||||
LocalFileWriter = SandboxedModule.require(modulePath, {
|
||||
requires: {
|
||||
fs,
|
||||
stream,
|
||||
'@overleaf/settings': settings,
|
||||
'@overleaf/metrics': {
|
||||
inc: sinon.stub(),
|
||||
Timer: sinon.stub().returns({ done: sinon.stub() }),
|
||||
},
|
||||
'@overleaf/object-persistor': ObjectPersistor,
|
||||
},
|
||||
})
|
||||
})
|
||||
|
||||
describe('writeStream', function () {
|
||||
it('writes the stream to the upload folder', function (done) {
|
||||
LocalFileWriter.writeStream(readStream, filename, (err, path) => {
|
||||
expect(err).not.to.exist
|
||||
expect(fs.createWriteStream).to.have.been.calledWith(fsPath)
|
||||
expect(stream.pipeline).to.have.been.calledWith(readStream, writeStream)
|
||||
expect(path).to.equal(fsPath)
|
||||
done()
|
||||
})
|
||||
})
|
||||
|
||||
describe('when there is an error', function () {
|
||||
const error = new Error('not enough ketchup')
|
||||
beforeEach(function () {
|
||||
stream.pipeline.yields(error)
|
||||
})
|
||||
|
||||
it('should wrap the error', function () {
|
||||
LocalFileWriter.writeStream(readStream, filename, err => {
|
||||
expect(err).to.exist
|
||||
expect(err.cause).to.equal(error)
|
||||
})
|
||||
})
|
||||
|
||||
it('should delete the temporary file', function () {
|
||||
LocalFileWriter.writeStream(readStream, filename, () => {
|
||||
expect(fs.unlink).to.have.been.calledWith(fsPath)
|
||||
})
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('deleteFile', function () {
|
||||
it('should unlink the file', function (done) {
|
||||
LocalFileWriter.deleteFile(fsPath, err => {
|
||||
expect(err).not.to.exist
|
||||
expect(fs.unlink).to.have.been.calledWith(fsPath)
|
||||
done()
|
||||
})
|
||||
})
|
||||
|
||||
it('should not call unlink with an empty path', function (done) {
|
||||
LocalFileWriter.deleteFile('', err => {
|
||||
expect(err).not.to.exist
|
||||
expect(fs.unlink).not.to.have.been.called
|
||||
done()
|
||||
})
|
||||
})
|
||||
|
||||
it('should not throw a error if the file does not exist', function (done) {
|
||||
const error = new Error('file not found')
|
||||
error.code = 'ENOENT'
|
||||
fs.unlink = sinon.stub().yields(error)
|
||||
LocalFileWriter.deleteFile(fsPath, err => {
|
||||
expect(err).not.to.exist
|
||||
done()
|
||||
})
|
||||
})
|
||||
|
||||
it('should wrap the error', function (done) {
|
||||
const error = new Error('failed to reticulate splines')
|
||||
fs.unlink = sinon.stub().yields(error)
|
||||
LocalFileWriter.deleteFile(fsPath, err => {
|
||||
expect(err).to.exist
|
||||
expect(err.cause).to.equal(error)
|
||||
done()
|
||||
})
|
||||
})
|
||||
})
|
||||
})
|
110
services/filestore/test/unit/js/SafeExecTests.js
Normal file
110
services/filestore/test/unit/js/SafeExecTests.js
Normal file
|
@ -0,0 +1,110 @@
|
|||
const chai = require('chai')
|
||||
const should = chai.should()
|
||||
const { expect } = chai
|
||||
const modulePath = '../../../app/js/SafeExec'
|
||||
const { Errors } = require('@overleaf/object-persistor')
|
||||
const SandboxedModule = require('sandboxed-module')
|
||||
|
||||
describe('SafeExec', function () {
|
||||
let settings, options, safeExec
|
||||
|
||||
beforeEach(function () {
|
||||
settings = { enableConversions: true }
|
||||
options = { timeout: 10 * 1000, killSignal: 'SIGTERM' }
|
||||
|
||||
const ObjectPersistor = { Errors }
|
||||
|
||||
safeExec = SandboxedModule.require(modulePath, {
|
||||
globals: { process },
|
||||
requires: {
|
||||
'@overleaf/settings': settings,
|
||||
'@overleaf/object-persistor': ObjectPersistor,
|
||||
},
|
||||
})
|
||||
})
|
||||
|
||||
describe('safeExec', function () {
|
||||
it('should execute a valid command', function (done) {
|
||||
safeExec(['/bin/echo', 'hello'], options, (err, stdout, stderr) => {
|
||||
stdout.should.equal('hello\n')
|
||||
stderr.should.equal('')
|
||||
should.not.exist(err)
|
||||
done()
|
||||
})
|
||||
})
|
||||
|
||||
it('should error when conversions are disabled', function (done) {
|
||||
settings.enableConversions = false
|
||||
safeExec(['/bin/echo', 'hello'], options, err => {
|
||||
expect(err).to.exist
|
||||
done()
|
||||
})
|
||||
})
|
||||
|
||||
it('should execute a command with non-zero exit status', function (done) {
|
||||
safeExec(['/usr/bin/env', 'false'], options, err => {
|
||||
expect(err).to.exist
|
||||
expect(err.name).to.equal('FailedCommandError')
|
||||
expect(err.code).to.equal(1)
|
||||
expect(err.stdout).to.equal('')
|
||||
expect(err.stderr).to.equal('')
|
||||
done()
|
||||
})
|
||||
})
|
||||
|
||||
it('should handle an invalid command', function (done) {
|
||||
safeExec(['/bin/foobar'], options, err => {
|
||||
err.code.should.equal('ENOENT')
|
||||
done()
|
||||
})
|
||||
})
|
||||
|
||||
it('should handle a command that runs too long', function (done) {
|
||||
safeExec(
|
||||
['/bin/sleep', '10'],
|
||||
{ timeout: 500, killSignal: 'SIGTERM' },
|
||||
err => {
|
||||
expect(err).to.exist
|
||||
expect(err.name).to.equal('FailedCommandError')
|
||||
expect(err.code).to.equal('SIGTERM')
|
||||
done()
|
||||
}
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
describe('as a promise', function () {
|
||||
beforeEach(function () {
|
||||
safeExec = safeExec.promises
|
||||
})
|
||||
|
||||
it('should execute a valid command', async function () {
|
||||
const { stdout, stderr } = await safeExec(['/bin/echo', 'hello'], options)
|
||||
|
||||
stdout.should.equal('hello\n')
|
||||
stderr.should.equal('')
|
||||
})
|
||||
|
||||
it('should throw a ConversionsDisabledError when appropriate', async function () {
|
||||
settings.enableConversions = false
|
||||
try {
|
||||
await safeExec(['/bin/echo', 'hello'], options)
|
||||
} catch (err) {
|
||||
expect(err.name).to.equal('ConversionsDisabledError')
|
||||
return
|
||||
}
|
||||
expect('method did not throw an error').not.to.exist
|
||||
})
|
||||
|
||||
it('should throw a FailedCommandError when appropriate', async function () {
|
||||
try {
|
||||
await safeExec(['/usr/bin/env', 'false'], options)
|
||||
} catch (err) {
|
||||
expect(err.name).to.equal('FailedCommandError')
|
||||
expect(err.code).to.equal(1)
|
||||
return
|
||||
}
|
||||
expect('method did not throw an error').not.to.exist
|
||||
})
|
||||
})
|
||||
})
|
21
services/filestore/test/unit/js/SettingsTests.js
Normal file
21
services/filestore/test/unit/js/SettingsTests.js
Normal file
|
@ -0,0 +1,21 @@
|
|||
const chai = require('chai')
|
||||
const { expect } = chai
|
||||
const SandboxedModule = require('sandboxed-module')
|
||||
|
||||
describe('Settings', function () {
|
||||
describe('s3', function () {
|
||||
it('should use JSONified env var if present', function () {
|
||||
const s3Settings = {
|
||||
bucket1: {
|
||||
auth_key: 'bucket1_key',
|
||||
auth_secret: 'bucket1_secret',
|
||||
},
|
||||
}
|
||||
process.env.S3_BUCKET_CREDENTIALS = JSON.stringify(s3Settings)
|
||||
const settings = SandboxedModule.require('@overleaf/settings', {
|
||||
globals: { console, process },
|
||||
})
|
||||
expect(settings.filestore.s3.bucketCreds).to.deep.equal(s3Settings)
|
||||
})
|
||||
})
|
||||
})
|
58
services/filestore/tiny.pdf
Normal file
58
services/filestore/tiny.pdf
Normal file
|
@ -0,0 +1,58 @@
|
|||
%PDF-1.1
|
||||
%¥±ë
|
||||
|
||||
1 0 obj
|
||||
<< /Type /Catalog
|
||||
/Pages 2 0 R
|
||||
>>
|
||||
endobj
|
||||
|
||||
2 0 obj
|
||||
<< /Type /Pages
|
||||
/Kids [3 0 R]
|
||||
/Count 1
|
||||
/MediaBox [0 0 300 144]
|
||||
>>
|
||||
endobj
|
||||
|
||||
3 0 obj
|
||||
<< /Type /Page
|
||||
/Parent 2 0 R
|
||||
/Resources
|
||||
<< /Font
|
||||
<< /F1
|
||||
<< /Type /Font
|
||||
/Subtype /Type1
|
||||
/BaseFont /Times-Roman
|
||||
>>
|
||||
>>
|
||||
>>
|
||||
/Contents 4 0 R
|
||||
>>
|
||||
endobj
|
||||
|
||||
4 0 obj
|
||||
<< /Length 55 >>
|
||||
stream
|
||||
BT
|
||||
/F1 18 Tf
|
||||
0 0 Td
|
||||
(Hello World) Tj
|
||||
ET
|
||||
endstream
|
||||
endobj
|
||||
|
||||
xref
|
||||
0 5
|
||||
0000000000 65535 f
|
||||
0000000018 00000 n
|
||||
0000000077 00000 n
|
||||
0000000178 00000 n
|
||||
0000000457 00000 n
|
||||
trailer
|
||||
<< /Root 1 0 R
|
||||
/Size 5
|
||||
>>
|
||||
startxref
|
||||
565
|
||||
%%EOF
|
0
services/filestore/uploads/.gitignore
vendored
Normal file
0
services/filestore/uploads/.gitignore
vendored
Normal file
0
services/filestore/user_files/.gitignore
vendored
Normal file
0
services/filestore/user_files/.gitignore
vendored
Normal file
Loading…
Reference in a new issue