Commit Graph

71 Commits

Author SHA1 Message Date
Tim Abbott 1ea2f188ce tornado: Rewrite Django integration to duplicate less code.
Since essentially the first use of Tornado in Zulip, we've been
maintaining our Tornado+Django system, AsyncDjangoHandler, with
several hundred lines of Django code copied into it.

The goal for that code was simple: We wanted a way to use our Django
middleware (for code sharing reasons) inside a Tornado process (since
we wanted to use Tornado for our async events system).

As part of the Django 2.2.x upgrade, I looked at upgrading this
implementation to be based off modern Django, and it's definitely
possible to do that:
* Continue forking load_middleware to save response middleware.
* Continue manually running the Django response middleware.
* Continue working out a hack involving copying all of _get_response
  to change a couple lines allowing us our Tornado code to not
  actually return the Django HttpResponse so we can long-poll.  The
  previous hack of returning None stopped being viable with the Django 2.2
  MiddlewareMixin.__call__ implementation.

But I decided to take this opportunity to look at trying to avoid
copying material Django code, and there is a way to do it:

* Replace RespondAsynchronously with a response.asynchronous attribute
  on the HttpResponse; this allows Django to run its normal plumbing
  happily in a way that should be stable over time, and then we
  proceed to discard the response inside the Tornado `get()` method to
  implement long-polling.  (Better yet might be raising an
  exception?).  This lets us eliminate maintaining a patched copy of
  _get_response.

* Removing the @asynchronous decorator, which didn't add anything now
  that we only have one API endpoint backend (with two frontend call
  points) that could call into this.  Combined with the last bullet,
  this lets us remove a significant hack from our
  never_cache_responses function.

* Calling the normal Django `get_response` method from zulip_finish
  after creating a duplicate request to process, rather than writing
  totally custom code to do that.  This lets us eliminate maintaining
  a patched copy of Django's load_middleware.

* Adding detailed comments explaining how this is supposed to work,
  what problems we encounter, and how we solve various problems, which
  is critical to being able to modify this code in the future.

A key advantage of these changes is that the exact same code should
work on Django 1.11, Django 2.2, and Django 3.x, because we're no
longer copying large blocks of core Django code and thus should be
much less vulnerable to refactors.

There may be a modest performance downside, in that we now run both
request and response middleware twice when longpolling (once for the
request we discard).  We may be able to avoid the expensive part of
it, Zulip's own request/response middleware, with a bit of additional
custom code to save work for requests where we're planning to discard
the response.  Profiling will be important to understanding what's
worth doing here.
2020-02-13 16:13:11 -08:00
Anders Kaseorg ea6934c26d dependencies: Remove WebSockets system for sending messages.
Zulip has had a small use of WebSockets (specifically, for the code
path of sending messages, via the webapp only) since ~2013.  We
originally added this use of WebSockets in the hope that the latency
benefits of doing so would allow us to avoid implementing a markdown
local echo; they were not.  Further, HTTP/2 may have eliminated the
latency difference we hoped to exploit by using WebSockets in any
case.

While we’d originally imagined using WebSockets for other endpoints,
there was never a good justification for moving more components to the
WebSockets system.

This WebSockets code path had a lot of downsides/complexity,
including:

* The messy hack involving constructing an emulated request object to
  hook into doing Django requests.
* The `message_senders` queue processor system, which increases RAM
  needs and must be provisioned independently from the rest of the
  server).
* A duplicate check_send_receive_time Nagios test specific to
  WebSockets.
* The requirement for users to have their firewalls/NATs allow
  WebSocket connections, and a setting to disable them for networks
  where WebSockets don’t work.
* Dependencies on the SockJS family of libraries, which has at times
  been poorly maintained, and periodically throws random JavaScript
  exceptions in our production environments without a deep enough
  traceback to effectively investigate.
* A total of about 1600 lines of our code related to the feature.
* Increased load on the Tornado system, especially around a Zulip
  server restart, and especially for large installations like
  zulipchat.com, resulting in extra delay before messages can be sent
  again.

As detailed in
https://github.com/zulip/zulip/pull/12862#issuecomment-536152397, it
appears that removing WebSockets moderately increases the time it
takes for the `send_message` API query to return from the server, but
does not significantly change the time between when a message is sent
and when it is received by clients.  We don’t understand the reason
for that change (suggesting the possibility of a measurement error),
and even if it is a real change, we consider that potential small
latency regression to be acceptable.

If we later want WebSockets, we’ll likely want to just use Django
Channels.

Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2020-01-14 22:34:00 -08:00
Anders Kaseorg 892e69b7ad settings: Turn on mypy checking.
Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2019-11-13 12:38:45 -08:00
Anders Kaseorg fc6a8396ed mypy: In non-daemon mode, follow package imports.
Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2019-08-16 14:13:40 -07:00
Anders Kaseorg a5596011a0 queue_processors, python_examples: Fix mypy errors.
zerver/openapi/python_examples.py:105: error: Argument 1 to "get_user_presence" of "Client" has incompatible type "str"; expected "Dict[str, Any]"
    zerver/openapi/python_examples.py:563: error: Argument 1 to "add_reaction" of "Client" has incompatible type "Dict[str, object]"; expected "Dict[str, str]"
    zerver/openapi/python_examples.py:576: error: Argument 1 to "remove_reaction" of "Client" has incompatible type "Dict[str, object]"; expected "Dict[str, str]"
    zerver/worker/queue_processors.py:587: error: Argument "client" to "extract_query_without_mention" has incompatible type "EmbeddedBotHandler"; expected "ExternalBotHandler"

These were only missed because mypy daemon mode requires us to set
`follow_imports = skip` for the `zulip` package.

Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2019-08-16 14:13:40 -07:00
Anders Kaseorg b0859f4b1e linter_lib: Fix mypy errors.
tools/linter_lib/pyflakes.py:35: error: Argument 3 to "run_pyflakes" has incompatible type "List[Tuple[bytes, bytes]]"; expected "List[Tuple[str, str]]"
    tools/linter_lib/custom_check.py:110: error: Argument "rules" to "RuleList" has incompatible type "List[Dict[str, Any]]"; expected "List[Rule]"
    tools/linter_lib/custom_check.py:214: error: Argument "rules" to "RuleList" has incompatible type "List[Dict[str, Any]]"; expected "List[Rule]"
    tools/linter_lib/custom_check.py:214: error: Argument "shebang_rules" to "RuleList" has incompatible type "List[Dict[str, Any]]"; expected "List[Rule]"
    tools/linter_lib/custom_check.py:502: error: Argument "rules" to "RuleList" has incompatible type "List[Dict[str, Any]]"; expected "List[Rule]"
    tools/linter_lib/custom_check.py:502: error: Argument "shebang_rules" to "RuleList" has incompatible type "List[Dict[str, Any]]"; expected "List[Rule]"
    tools/linter_lib/custom_check.py:519: error: Argument "rules" to "RuleList" has incompatible type "List[Dict[str, Any]]"; expected "List[Rule]"
    tools/linter_lib/custom_check.py:706: error: Argument "rules" to "RuleList" has incompatible type "List[Dict[str, Any]]"; expected "List[Rule]"
    tools/linter_lib/custom_check.py:728: error: Argument "rules" to "RuleList" has incompatible type "List[Dict[str, Any]]"; expected "List[Rule]"
    tools/linter_lib/custom_check.py:738: error: Argument "rules" to "RuleList" has incompatible type "List[Dict[str, Any]]"; expected "List[Rule]"
    tools/linter_lib/custom_check.py:779: error: Argument "rules" to "RuleList" has incompatible type "List[Dict[str, Any]]"; expected "List[Rule]"
    tools/linter_lib/custom_check.py:779: error: Argument "length_exclude" to "RuleList" has incompatible type "Set[str]"; expected "List[str]"
    tools/linter_lib/custom_check.py:803: error: Argument "length_exclude" to "RuleList" has incompatible type "Set[str]"; expected "List[str]"
    tools/linter_lib/custom_check.py:805: error: Unsupported operand types for + ("List[Rule]" and "List[Dict[str, Any]]")
    tools/linter_lib/custom_check.py:819: error: Argument "rules" to "RuleList" has incompatible type "List[Dict[str, Any]]"; expected "List[Rule]"

These were missed the `zulint` package was missing PEP 561 type
annotation markers, and if it’d had them, mypy daemon mode would’ve
required us to set `follow_imports = skip` for it.

Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2019-08-09 17:22:45 -07:00
Wyatt Hoodes 8c26183c65 mypy: Assign warn_unreachable in mypy.ini.
Instead of doing this rather clumsily in `run_mypy`,
we configure the option in `mypy.ini`.
2019-08-06 12:43:29 -07:00
Anders Kaseorg bc9d7141b2 mypy: Enable strict_optional for test_outgoing_webhook_interfaces.
Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2019-05-04 23:15:58 -07:00
neiljp (Neil Pilgrim) 4ea5fea8a1 mypy: Fully check actions.py by removing mypy.ini special case. 2019-05-01 17:52:37 -07:00
neiljp (Neil Pilgrim) 827c016b98 mypy: Enable strict-optional for messages.py.
This also fixes an issue where we were setting num_after to None,
which should have been 0, to disable fetching messages after the
anchor.
2019-05-01 11:24:47 -07:00
neiljp (Neil Pilgrim) 3d43682f1b mypy: Enable strict-optional for auth.py. 2019-05-01 10:49:25 -07:00
neiljp (Neil Pilgrim) f3ef2a186c mypy: Enable strict-optional for calculate_first_visible_message_id. 2019-05-01 10:49:24 -07:00
Tim Abbott 612e70a64b docs: Add a warning about editing mypy stubs and the daemon. 2018-12-17 10:28:18 -08:00
neiljp (Neil Pilgrim) c3cd3e94c1 mypy: Add Optional & check in zproject/backends.py; remove from mypy.ini. 2018-10-29 12:53:16 -07:00
neiljp (Neil Pilgrim) 482383b6f7 mypy: Add Optional to tornado/descriptors.py; remove from mypy.ini. 2018-10-29 12:53:16 -07:00
neiljp (Neil Pilgrim) a2767df51d mypy: Enforce strict-optional checking of decorator.py. 2018-10-25 07:24:47 -05:00
neiljp (Neil Pilgrim) 06c2748a98 mypy: Remove various mypy.ini exclusions due to REQ/None.
Current mypy supports returning None without error.
See python/mypy#4214.
2018-10-25 07:24:47 -05:00
Greg Price a8f66573f3 mypy: Switch back to a blanket `ignore_missing_imports = True`.
Since pushing this down to specific modules in 8ca31773c, we've
had to do bookkeeping here for every new dependency we add, unless
we add stubs for it at the same time -- which we never have.

That'd be fine if we were burning down this list and on track to
eliminate it soon, but we aren't.  So, go back to a global
acknowledgement that we have a lot of untyped dependencies.  The
stubs we do have will work just the same, and we can keep adding
more for whatever libraries we choose to.
2018-08-06 12:14:36 -07:00
Greg Price 5b99223814 mypy: Correct the story about skipping `zulip`.
Also remove the ignore_missing_imports on it, which has no effect.
That setting only does anything when mypy doesn't know where to find
the module; follow_imports only does anything when it does know.

See upstream docs:
  http://mypy.readthedocs.io/en/latest/config_file.html#per-module-flags

(I confirmed with `strace -f -efile` that the place mypy is finding
the `zulip` module is in fact in the virtualenv.)
2018-08-06 12:08:08 -07:00
Tim Abbott c0beeebc3e zulint: Move printer.py module to tools/zulint.
At this point, tools/linter_lib is intended to be the directory of
Zulip-specific code.
2018-08-04 19:53:53 -07:00
Tim Abbott acf8ec492d zulint: Extract common linter argument parsing logic.
The remaining code is Zulip-specific business logic.
2018-08-04 19:53:53 -07:00
Tim Abbott 1fcc2a6ea4 zulint: Move lister.py to tools/zulint.
This is preparatory refactoring work for being able to extract the
linter as an external project called "zulint".
2018-08-04 19:53:53 -07:00
Harshit Bansal 25fa9a25ff emoji: Add support for animated GIF images.
This commit adds 'resize_gif()' function which extracts each frame,
resize it and coalesces them again to form the resized GIF while
preserving the duration of the GIF. I read some stackoverflow
answers all of which were referring to BiggleZX's script
(https://gist.github.com/BigglesZX/4016539) for working with animated
GIF. I modified the script to fit to our usecase and did some manual
testing but the function was failing for some specific GIFs and was not
preserving the duration of animation. So I went ahead and read about
GIF format itself as well as PIL's `GifImagePlugin` code and came up
with this simple function which gets the worked done in a much cleaner
way. I tested this function on a number of GIF images from giphy.com
and it resized all of them correctly.

Fixes: #9945.
2018-08-04 11:46:58 -07:00
Rhea Parekh b8e1e8b31d import: Add slack import files in zerver/data_import directory. 2018-08-01 11:52:14 -07:00
Vishnu Ks abf485bfcb billing: Add mypy stubs to stripe imports.
Tweaked by tabbott to add an extra type: ignore.
2018-07-26 16:31:32 -07:00
Aditya Bansal 98a4e87e1d thumbor: Complete implementation of thumbnailing.
Various pieces of our thumbor-based thumbnailing system were already
merged; this adds the remaining pieces required for it to work:

* a THUMBOR_URL Django setting that controls whether thumbor is
  enabled on the Zulip server (and if so, where thumbor is hosted).

* Replaces the overly complicated prototype cryptography logic

* Adds a /thumbnail endpoint (supported both on web and mobile) for
  accessing thumbnails in messages, designed to support hosting both
  external URLs as well as uploaded files (and applying Zulip's
  security model for access to thumbnails of uploaded files).

* Modifies bugdown to, when THUMBOR_URL is set, render images with the
  `src` attribute pointing /thumbnail (to provide a small thumbnail
  for the image), along with adding a "data-original" attribute that
  can be used to access the "original/full" size version of the image.

There are a few things that don't work quite yet:
* The S3 backend support is incomplete and doesn't work yet.
* The error pages for unauthorized access are ugly.
* We might want to rename data-original and /thumbnail?size=original
  to use some other name, like "full", that better reflects the fact
  that we're potentially not serving the original image URL.
2018-07-15 00:39:41 +05:30
Tim Abbott 52f5d83c90 thumbor: Add libthumbor dependency.
We need this for signing thumbnail requests from within Zulip.
2018-07-14 21:46:02 +05:30
Greg Price 6d44772925 mypy: Add a first stub file, for yamole.
The main purpose of this commit is to demonstrate end-to-end that
our setup for type stubs works.  I picked this library more or less
arbitrarily as one where the API surface we use is tiny, so that the
stub would be extra easy to write.
2018-07-12 14:10:53 +05:30
Greg Price 36cf898589 mypy: Add a place to put type stubs.
This will allow us to begin to add our own stubs for external
libraries.  Writing stubs can be surprisingly little work to do, and
can have high leverage in keeping our type annotations high-quality.
2018-07-12 14:10:09 +05:30
neiljp (Neil Pilgrim) 88a70c5f5d mypy: test_embedded_bot_system.py: add asserts & remove from mypy.ini. 2018-06-19 10:48:38 -07:00
neiljp (Neil Pilgrim) b5aa705137 mypy: test_link_embed.py: add assert & remove from mypy.ini. 2018-06-19 10:48:38 -07:00
Tim Abbott 9a0a947dc1 mypy: Fix errors when trying to find the zulip Python project. 2018-06-04 11:48:36 -07:00
Tim Abbott 0d84eb0a8b mypy: Clean zerver/views/users.py for strict-optional. 2018-06-01 08:48:17 -07:00
Yago González f84c9b919b api docs: Read parameters and response fixtures from OpenAPI files. 2018-05-26 22:49:55 +02:00
Umair Khan a2d3aea027 2FA: Add two-factor related code.
This commit adds a view which will be used to process login requests,
adds an AuthenticationTokenForm so that we can use TextField widget for
tokens, and activates two factor authentication code path whenever user
tries to login.
2018-05-23 15:46:56 -07:00
Michael J. Sullivan c4bd0e5791 mypy: Switch to follow_imports = error.
The mypy daemon only supports error and skip. Choosing error
immediately surfaces when a file excluded from the build is
being imported, so that something can be done about it.
2018-05-21 22:41:02 -07:00
Michael J. Sullivan d5ee801d60 mypy: Set local_partial_types = True.
The daemon implicitly sets this flag, so set it explicitly and fix all
of the type errors.
2018-05-21 22:41:00 -07:00
Greg Price 3498fc4e74 mypy: Partially revert "Revert "test_helpers: Fix a nonexistent import."".
Commit fa18913b8 preserved the fix to the actual import, but added
back the `ignore_missing_imports` line that had shielded the
erroneous import.  Remove that line again.
2018-05-21 14:58:12 -07:00
Tim Abbott 2cc5d2d398 requirements: Add httpretty to dependencies.
We'll be using this for a range of testing mocks in our auth code.
2018-05-20 23:31:36 -07:00
Tim Abbott 4f4d56b021 tornado: Import autoreload module from upstream Tornado.
This allows to patch things directly.
2018-05-20 16:49:17 -07:00
jkiely aa8248e734 mypy: Enable strict optional for check redis management command
Removed the error handling on the get_user_profile_by_id function, as it
would have just caused a different error shortly after.
2018-05-17 13:44:35 -07:00
jkiely d5e7b9599d mypy: Remove unnecessary blocks for strict optional=True. 2018-05-17 12:13:53 -07:00
jkiely 058ee1ce1e mypy: Enable strict optional on lib/soft_deactivation.
Tweaked by tabbott to add assert statements, rather than new
conditionals.
2018-05-17 12:13:53 -07:00
jkiely 104fdd8bf9 mypy: enable strict optional for lib/message.
Add assert in order to pass checks under strict conditions.
2018-05-17 11:12:08 -07:00
jkiely 04c50cffa7 mypy: Enable strict optional in zerver/lib/bugdown.
Explicitly check for none in optional value and set it to a dict.
2018-05-17 11:12:01 -07:00
jkiely b3d43df498 mypy: Enable strict optional for lib/exceptions.
Change return type of reduce_ex to pass under stricter conditions.
2018-05-17 11:11:58 -07:00
jkiely ca3ce90496 mypy: Enable strict optional in lib/avatar.py.
Add assert to function and modify tests in order to pass under
strict conditions.
2018-05-17 11:11:55 -07:00
jkiely a1b5e7d6d5 mypy: Enable strict optional in lib/events.
Modify one variable assignment to pass under strict conditions.
2018-05-17 11:11:53 -07:00
jkiely ad065fde29 mypy: Enable strict optional for lib/notifications.
Modify fix_emojis function to pass under strict conditions.
2018-05-17 11:11:49 -07:00
Tim Abbott 495104bd56 mypy: Clean test_subs.py of mypy strict-optional errors.
Most of this is just asserting that the sub_dict return value from
access_stream_by_id is not None in the cases where it shouldn't be,
but additionally, we also need to pass a function into
validate_user_access_to_subscribers_helper (in this case, just `lambda:
True` works fine)
2018-05-16 12:09:52 -07:00