Commit Graph

113 Commits

Author SHA1 Message Date
benedikt-bartscher
3039b54a75
add module prefix to generated state names (#3214)
* add module prefix to state names

* fix state names in test_app

* update state names in test_state

* fix state names in test_var

* fix state name in test_component

* fix state names in test_format

* fix state names in test_foreach

* fix state names in test_cond

* fix state names in test_datatable

* fix state names in test_colors

* fix state names in test_script

* fix state names in test_match

* fix state name in event1 fixture

* fix pyright and darglint

* fix state names in state_tree

* fix state names in redis only test

* fix state names in test_client_storage

* fix state name in js template

* add `get_state_name` and `get_full_state_name` helpers for `AppHarness`

* fix state names in test_dynamic_routes

* use new state name helpers in test_client_storage

* fix state names in test_event_actions

* fix state names in test_event_chain

* fix state names in test_upload

* fix state name in test_login_flow

* fix state names in test_input

* fix state names in test_form_submit

* ruff

* validate state module names

* wtf is going on here?

* remove comments leftover from refactoring

* adjust new test_add_style_embedded_vars

* fix state name in state.js

* fix integration/test_client_state.py

new SessionStorage feature was added with more full state names that need to be formatted in

* fix pre-commit issues in test_client_storage.py

* adjust test_computed_vars

* adjust safe-guards

* fix redis tests with new exception state

---------

Co-authored-by: Masen Furer <m_github@0x26.net>
2024-07-11 11:13:57 -07:00
Maxim Vlah
772a3ef893
Catch unhandled errors on both frontend and backend (#3572) 2024-07-08 19:26:11 -07:00
benedikt-bartscher
b7651e214b
add computed backend vars (#3573)
* add computed backend vars

* finish computed backend vars, add tests

* fix token for AppHarness with redis state manager

* fix timing issues

* add unit tests for computed backend vars

* automagically mark cvs with _ prefix as backend var

* fully migrate backend computed vars

* rename is_backend_variable to is_backend_base_variable

* add integration test for implicit backend cv, adjust comments

* replace expensive backend var check at runtime

* keep stuff together

* simplify backend var check method, consistent naming, improve test typing

* fix: do not convert properties to cvs

* add test for property

* fix cached_properties with _ prefix in state cls
2024-06-28 17:01:07 -07:00
Elijah Ahianyo
8f2cbb5ea1
[REF-2588]Clear color mode local storage for dev mode (#3548)
* Clear color mode local storage

* use the last compiled time logic to determine when to clear local storage

* precommit fix

* app harness fix

* run prettier on reflex/.templates/web/utils/helpers/color_mode.js

* make sure last_compiled_time is updated for stateless apps as well.

* set the chkara-ui-color-mode cookie instead of clearing it, so it is integrated in the app's useEffect cycle

* fix CI

* fix import formatting

---------

Co-authored-by: Masen Furer <m_github@0x26.net>
2024-06-28 13:57:34 -07:00
benedikt-bartscher
a7e4594fdc
Deprecate cached var (#3582)
* deprecate cached_var partial

* migrate cached_var to var(cache=True)

* fix darglint (typo)
2024-06-28 10:14:55 -07:00
benedikt-bartscher
8e66c9b3c7
classvars should not be backend vars (#3578)
* classvars should not be backend vars

* cleanup RESERVED_BACKEND_VAR_NAMES
2024-06-27 16:03:36 -07:00
benedikt-bartscher
41efe12e9a
Validate ComputedVar dependencies, add tests (#3527) 2024-06-24 16:11:42 -07:00
Masen Furer
c2c6286537
Always treat the call_script callback as a string of JS code (#3521) 2024-06-20 18:05:25 -07:00
Thomas Brandého
0d39237b3c
upgrade to latest ruff (#3497)
* upgrade to latest ruff

* try to fix dep review

* try to fix dep review (2)

* upgrade black

* upgrade black (2)

* update allowed dependencies

* update allowed dependencies (2)

* update allowed dependencies (3)

* wait between interim and final in yield test

* remove previous commit, increase delay between yield

* forgot to save on the time.sleep(1) removal

* fix integration (maybe?)

* fix pyi?

* what even is going on

* what is realityi?

* test another fix for app harness

* try to wait even longer?

* force uvloop to be optional

* downpin fastapi < 0.111, remove changes to test
2024-06-19 12:32:13 +02:00
Masen Furer
af3c9be97c
Protect StateProxy with an asyncio.Lock (#3508)
* test_background_task: dispatch multiple async tasks

Use asyncio.gather to dispatch multiple tasks from a single background task
that all compete over the `async with self` lock. Even though the state itself
has a lock, each StateProxy instance should only allow a single `async with
self` context to run at a time.

* Protect StateProxy with an asyncio.Lock

Allow multiple tasks to reference the same StateProxy without stomping on each
other when entering an `async with self` context to acquire the state lock and
ultimately modify the state.
2024-06-18 09:48:12 -07:00
Kelechi Ebiri
2b2cdf9847
Feat: Add Session storage to store data on client storage (#3420) 2024-06-17 17:31:36 -04:00
Masen Furer
e138d9dfd0
state.js: set event_processing = false when websocket connects (#3443)
* test_connection_banner: Improve assertions

* Actually assert on the presence or absense of the connection banner
* Update XPATH selector to find the connection toast
* Add event handling while backend down to verify queue functionality
* Bring backend down while an event is running to ensure queue does not get
  blocked (#3404)

* state.js: set event_processing = false when websocket connects

In case an event was pending when the websocket went down, allow further events
to be processed when it comes back up.

Fix #3404

* test_connection_banner: wait for token indicating backend is connected

* test_connection_banner: increase delay time

make the time window longer in which the backend can go down and get stuck in
event_processing=true for better test reliability

* Ensure the redis connection is reset in new backend thread

Redis has an event loop affinity and needs to be attached to the event loop
that the thread is running.

* Reset event_processing on disconnect

* if the socket never comes back up, it still allows client-side events to be
  processed
* on_mount events may start running before the socket is up, so resetting the
  flag on connect may break event determinism (test_event_chain.py)
2024-06-07 13:29:25 -07:00
Masen Furer
765f349f02
[REF-3004] Use relative path to stylesheet for postcss-import compat (#3435)
* test_tailwind: include custom stylesheet

* [REF-3004] Use relative path to stylesheet for postcss-import compat

postcss-import balls all of the CSS up into a single file, which happens at
compile time. So, replace the `@/` with `../public` so the import paths can be
resolved relative to the `styles` directory.

* test_compiler: fix compile_stylesheets expectations

* Use constants.Dirs.PUBLIC instead of "public"
2024-06-05 10:02:05 -07:00
Elijah Ahianyo
34bf25071a
[REF-2821]Improve Dynamic Imports (#3345)
* Improve import times

* add lazy loading to rx.el

* add lazy loading to reflex core components

* minor refactor

* Get imports working with reflex web

* get imports to work with all reflex examples

* refactor to define imports only in the root.

* lint

* deadcode remove

* update poetry deps

* unit tests fix

* app_harness fix

* app_harness fix

* pyi file generate

* pyi file generate

* sort pyi order

* fix pyi

* fix docker ci

* rework pyi-generator

* generate pyi for __init__ files

* test pyright

* test pyright ci

* partial pyright fix

* more pyright fix

* pyright fix

* fix pyi_generator

* add rx.serializer and others

* add future annotation import which fixes container CI, then also load recharts lazily

* add new pyi files

* pyright fix

* minor fixes for reflex-web and flexdown

* forward references for py38

* ruff fix

* pyi fix

* unit tests fix

* reduce coverage to 68%

* reduce coverage to 67%

* reduce coverage to 66%as a workaround to coverage's rounding issue

* reduce coverage to 66%as a workaround to coverage's rounding issue

* exclude lazy_loader dependency review checks.

* its lazy-loader

* Add docstrings and regenerate pyi files

* add link

* address Pr comments

* CI fix

* partially address PR comments.

* edit docstrings and fix integration tests

* fix typo in docstring

* pyi fix
2024-05-31 16:43:10 +00:00
benedikt-bartscher
93de407007
Explicit deps and interval for computed vars (#3231) 2024-05-28 12:27:27 -07:00
benedikt-bartscher
d96f051486
set config.deploy_url during AppHarness tests (#3359) 2024-05-23 09:23:07 -07:00
Thomas Brandého
956a526b20
add support for lifespan tasks (#3312)
* add support for lifespan tasks

* allow passing args to lifespan task

* add message to the cancel call

* allow asynccontextmanager as lifespan tasks

* Fix integration.utils.SessionStorage

Previously the SessionStorage util was just looking in localStorage, but the
tests didn't catch it because they were asserting the token was not None,
rather than asserting it was truthy.

Fixed here, because I'm using this structure in the new lifespan test.

* If the lifespan task or context takes "app" parameter, pass the FastAPI instance.

* test_lifespan: end to end test for register_lifespan_task

* In py3.8, Task.cancel takes no args

* test_lifespan: use polling to make the test more robust

Fix CI failure

* Do not allow task_args for better composability

---------

Co-authored-by: Masen Furer <m_github@0x26.net>
2024-05-22 12:07:03 -07:00
benedikt-bartscher
d96baac7d9
typed mixins and ComponentState (#3196)
* typed mixins

* implicit mixin=True kwarg for ComponentState subclasses

* fix: always init other subclasses

* adjust tests: all mixins support base vars now
2024-05-15 12:07:41 -07:00
benedikt-bartscher
1324947f3c
minor test exp_not_equal fixup (#3256) 2024-05-08 13:34:17 -07:00
benedikt-bartscher
f0a772d08c
fix screenshot filenames (#3241) 2024-05-07 19:31:37 -07:00
Masen Furer
ea0f490030
[REF-2764] dep update 0.5.0 (#3245)
* upgrade to latest pip for in_docker_test_script.sh

* Bump gunicorn to 22.0.0 (security)

Changelog: https://docs.gunicorn.org/en/stable/news.html#id1

use utime to notify workers liveness
migrate setup to pyproject.toml
fix numerous security vulnerabilities in HTTP parser (closing some request smuggling vectors)
parsing additional requests is no longer attempted past unsupported request framing
on HTTP versions < 1.1 support for chunked transfer is refused (only used in exploits)
requests conflicting configured or passed SCRIPT_NAME now produce a verbose error
Trailer fields are no longer inspected for headers indicating secure scheme
support Python 3.12

** Breaking changes **
minimum version is Python 3.7
the limitations on valid characters in the HTTP method have been bounded to Internet Standards
requests specifying unsupported transfer coding (order) are refused by default (rare)
HTTP methods are no longer casefolded by default (IANA method registry contains none affected)
HTTP methods containing the number sign (#) are no longer accepted by default (rare)
HTTP versions < 1.0 or >= 2.0 are no longer accepted by default (rare, only HTTP/1.1 is supported)
HTTP versions consisting of multiple digits or containing a prefix/suffix are no longer accepted
HTTP header field names Gunicorn cannot safely map to variables are silently dropped, as in other software
HTTP headers with empty field name are refused by default (no legitimate use cases, used in exploits)
requests with both Transfer-Encoding and Content-Length are refused by default (such a message might indicate an attempt to perform request smuggling)
empty transfer codings are no longer permitted (reportedly seen with really old & broken proxies)

** SECURITY **
fix CVE-2024-1135

* Remove TYPE_CHECKING guard for pydantic v1 imports

Retain TYPE_CHECKING guard in v1 fallback to force pyright into pydantic.v1 namespace

* Run unit tests with pydantic v1 now that v2 is installed via poetry
2024-05-07 15:15:52 -07:00
Masen Furer
3564df7620
Implement throttle and debounce as event actions (#3091) 2024-04-26 17:28:51 -07:00
Masen Furer
74eaab5e19
Integration testing: Firefox compatibility (#3162)
* Integration testing: Firefox compatibility

* test_client_side_storage: ruff format
2024-04-26 13:44:08 -07:00
Thomas Brandého
ac36bfc6ea
Radix 3.0 (#3159) 2024-04-25 08:33:29 -07:00
Ogidi Ifechukwu
ce2bd2286e
Refactor upload component and add styled upload component (#3035) 2024-04-24 13:45:22 -07:00
Jirka Borovec
4d567b7ec1
ruff-format: unify Black with Ruff v0.1 (#2837)
* ruff-format: unify Black with Ruff

* ruff lint.

* v0.1.0

* run precommit

* hand fixing

* fix `not isinstance(...)`

Co-authored-by: Thomas Brandého <thomas.brandeho@gmail.com>

* rev isinstance(...) with noqa

* exclude = ["*.pyi"]

* apply precommit

* apply format

* revert pyi

* fixing

* Fix or

Co-authored-by: Thomas Brandého <thomas.brandeho@gmail.com>

* Update reflex/components/datadisplay/code.pyi

* Apply suggestions from code review

Co-authored-by: Thomas Brandého <thomas.brandeho@gmail.com>

* Update tests/components/core/test_colors.py

* Update reflex/app.py

* Update reflex/app.py

* Update benchmarks/test_benchmark_compile_pages.py

* Update benchmarks/test_benchmark_compile_pages.py

* Update benchmarks/test_benchmark_compile_pages.py

---------

Co-authored-by: Thomas Brandého <thomas.brandeho@gmail.com>
2024-04-23 14:40:06 -07:00
Martin Xu
7d36610cae
Support reflex app creation from templates from github (#2490) 2024-04-04 15:31:34 -07:00
Masen Furer
5510eaf820
[REF-2265] ComponentState: scaffold for copying State per Component instance (#2923)
* [REF-2265] ComponentState: scaffold for copying State per Component instance

Define a base ComponentState which can be used to easily create copies of the
given State definition (Vars and EventHandlers) that are tied to a particular
instance of a Component (returned by get_component)

* Define `State` field on `Component` for typing compatibility.

This is an Optional field of Type[State] and is populated by ComponentState.

* Add integration/test_component_state.py

Create two independent counters and increment them separately

* Add unit test for ComponentState
2024-03-29 09:22:25 -07:00
benedikt-bartscher
f27eae7655
fix AppHarness reloading (#2916)
* move AppHarness tests to module scope

* fix AppHarness reloading

* add test

* docstrings and formatting

* fix benchmarks not reloading state module
2024-03-26 11:09:46 -07:00
Masen Furer
e3db9adc70
Fix py3.8 integration test_var_operations.py (#2858)
A newly added test was not py3.8 compatible and is breaking CI runs
2024-03-13 17:45:27 -07:00
Elijah Ahianyo
a06b570e3a
Benchmark with app harness (#2774) 2024-03-13 15:59:55 -07:00
Masen Furer
036afa951a
Make @rx.memo work with state vars passed as props (#2810)
* Make @rx.memo work with state vars passed as props

Seems like this was a regression from the StatefulComponent refactor, because
trying to pass a state Var to a CustomComponent gave undefined, likely due to
`_get_vars` not accounting for `self.props` in CustomComponents.

With this change, it works.

Integration test added to `test_var_operations.py`

* Allow CustomComponent props to be Component

Avoid calling `.json()` on all Base types because the Var serializer already
does that, but this way, more specific types (like Component) can be serialized
differently.

When the type is Component, attach a VarData with the imports and hooks to when
the Var is rendered, it also carries the correct imports/hooks and does not
throw frontend errors.
2024-03-13 13:41:17 -07:00
Masen Furer
eb18ce90d5
[REF-2172] Add DECORATED_PAGES before compiling in thread (#2841) 2024-03-12 10:28:37 -07:00
benedikt-bartscher
19a5cdd408
Track state usage (#2441)
* rebase

* pass include_children kwarg in radix FormRoot

* respect include_children

* ruff fixes

* readd statemanager init, run pyi gen

* minor performance imporovements, fix for state changes

* fix pyi and pyright

* pass include_children for chakra

* remove old state detection

* add test for unused states in stateless app

---------

Co-authored-by: Masen Furer <m_github@0x26.net>
2024-03-07 14:25:55 -08:00
Masen Furer
5d647a498f
[REF-1368] Move common form functionality to rx.el.forms (#2801)
* [REF-1368] Move common form functionality to rx.el.forms

Allow plain HTML Form element to have magic on_submit event handler.

* Chakra and Radix forms inherit `on_submit` functionality from rx.el.form

Consolidate logic in the basic HTML form and use it in both Radix and Chakra
form wrappers.

* from __future__ import annotations for py38
2024-03-07 13:17:54 -08:00
Tom Gotsman
93fc269860
initial attempt at writing test for urls (#2689)
* initial attempt at writing test for urls

* turn it into a pytest test

* fix precommit and add wrong url to make sure test work

* fix darglint error and fix url set error

* black error

* add to test .md files in reflex as well

* update to fix masen comment

* black formatting

* Fix trailing slash in reflex/state.py

---------

Co-authored-by: Tom Gotsman <tomgotsman@Toms-MacBook-Pro.local>
Co-authored-by: Tom Gotsman <tomgotsman@toms-mbp.lan>
Co-authored-by: Masen Furer <m_github@0x26.net>
2024-02-29 13:45:57 -08:00
benedikt-bartscher
c465b94016
add some backend var state inheritance tests (#2685) 2024-02-28 15:11:14 -08:00
Masen Furer
3c3c331856
[REF-2101] Support default_value and default_checked on rx.el.input (#2739) 2024-02-27 16:57:37 -08:00
Masen Furer
deae662e2a
[REF-1988] API to Get instance of Arbitrary State class (#2678)
* WiP get_state

* Refactor get_state fast path

Rudimentary protection for state instance access from a background task
(StateProxy)

* retain dirty substate marking per `_mark_dirty` call to avoid test changes

* Find common ancestor by part instead of by character

Fix StateProxy for substates and parent_state attributes (have to handle in
__getattr__, not property)

Fix type annotation for `get_state`

* test_state: workflow test for `get_state` functionality

* Do not reset _always_dirty_substates when adding vars

Reset the substate tracking only when the class is instantiated.

* test_state_tree: test substate access in a larger state tree

Ensure that `get_state` returns the proper "branch" of the state tree depending
on what substate is requested.

* test_format: fixup broken tests from adding substates of TestState

* Fix flaky integration tests with more polling

* AppHarness: reset _always_dirty_substates on rx.State

* RuntimeError unless State is instantiated with _reflex_internal_init=True

Avoid user errors trying to directly instantiate State classes

* Helper functions for _substate_key and _split_substate_key

Unify the implementation of generating and decoding the token + state name
format used for redis state sharding.

* StateManagerRedis: use create_task in get_state and set_state

read and write substates concurrently (allow redis to shine)

* test_state_inheritance: use polling cuz life too short for flaky tests

kthnxbai ❤️

* Move _is_testing_env to reflex.utils.exec.is_testing_env

Reuse the code in app.py

* Break up `BaseState.get_state` and friends into separate methods

* Add test case for pre-fetching cached var dependency

* Move on_load_internal and update_vars_internal to substates

Avoid loading the entire state tree to process these common internal events. If
the state tree is very large, this allow page navigation to occur more quickly.

Pre-fetch substates that contain cached vars, as they may need to be recomputed
if certain vars change.

* Do not copy ROUTER_DATA into all substates.

This is a waste of time and memory, and can be handled via a special case in
__getattribute__

* Track whether State instance _was_touched

Avoid wasting time serializing states that have no modifications

* Do not persist states in `StateManagerRedis.get_state`

Wait until the state is actually modified, and then persist it as part of `set_state`.

Factor out common logic into helper methods for readability and to reduce
duplication of common logic.

To avoid having to recursively call `get_state`, which would require persisting
the instance and then getting it again, some of the initialization logic
regarding parent_state and substates is duplicated when creating a new
instance. This is for performance reasons.

* Remove stray print()

* context.js.jinja2: fix check for empty local storage / cookie vars

* Add comments for onLoadInternalEvent and initialEvents

* nit: typo

* split _get_was_touched into _update_was_touched

Improve clarity in cases where _get_was_touched was being called for its side
effects only.

* Remove extraneous information from incorrect State instantiation error

* Update missing redis exception message
2024-02-27 13:02:08 -08:00
Krys
278183b526
fix image serializing - REF-1889 (#2550)
* fix image serializing

* If get_format_mimetype does not work, look up format in Image.MIME

Throw a warning if the image format does not have an associated MIME type and
ultimately fallback to image/png and let the browser figure it out.

* test_media: end to end serialization of PIL images

---------

Co-authored-by: Masen Furer <m_github@0x26.net>
2024-02-22 08:13:19 -08:00
Masen Furer
789d50e0e4
test_input: replace sleep with _poll_for (#2677)
Reduce test flakiness and improve runtime in optimal case
2024-02-21 20:12:31 -08:00
Masen Furer
756bf9b0f4
[REF-1885] Shard Substates when serializing to Redis (#2574)
* Move sharding internal to StateManager

Avoid leaking sharding implementation details all over the State class and
breaking the API

* WiP StateManager based sharding

* Copy the state __dict__ when serializing to avoid breaking the instance

* State tests need to pass the correct substate token for redis

* state: when getting parent_state, set top_level=False

ensure that we don't end up with a broken tree

* test_app: get tests passing with redis by passing the correct token

refactor upload tests to suck less

* test_client_storage: look up substate key

* state.py: pass static checks

* test_dynamic_routes: working with redis state shard

* Update the remaining AppHarness tests to pass {token}_{state.get_full_name()}

* test_app: pass all tokens with state suffix

* StateManagerRedis: clean up commentary
2024-02-21 01:50:25 -08:00
abulvenz
980834605b
feat: Synchronizing localStorage between tabs using browser events (#2533)
* feat: Synchronizing localStorage between tabs using browser events

* test_client_storage: Test sync'd local storage vars

* update_vars_internal: generic handler to apply var changes to state tree

Apply fully qualified var names to each substate they are associated with. This
allows consistent updates to arbitrary state vars without having to know their
"setter" arguments, in case the user has overwritted the `set_x` name.

---------

Co-authored-by: Masen Furer <m_github@0x26.net>
2024-02-20 15:14:55 -08:00
Masen Furer
279e9bfa28
[REF-1993] link: respect is_external prop and other attributes on A tag (#2651)
* link: respect `is_external` prop and other attributes on A tag

Instead of passing all props to NextLink by default, only pass props that
NextLink understands, placing the remaining props on the Radix link

Add a test case to avoid regression of `is_external` behavior.

* Link is a MemoizationLeaf

Because Link is often rendered with NextLink as_child, and NextLink breaks if
the href is stateful outside of a Link, ensure that any stateful child of Link
gets memoized together.
2024-02-19 15:43:27 -08:00
Masen Furer
4206afeb7b
[REF-1958] Remove shadowed radix css props (#2590)
* style: shorthand replacements need camelCase

Avoid warning on terminal and in browser console from using kebab-case CSS
props with emotion.

* _rename_props only replace prop name once

In case the value also contains the prop name, we don't want to replace it
multiple times.

* pyi_generator: ignore _rename_props in create signature

* Avoid shadowing CSS prop `display` and `gap`

Replace usages of `gap` with `spacing` to retain Radix sizing number system,
while allowing users to specify a responsive `gap` using CSS units.

Remove `display` props from radix components, allowing `display` to accept
responsive lists.

* checkbox: apply `gap` to `flex` if provided

* Remove _rename_props from .create signatures

* Fix spacing prop in blank template

* Fixup tests after changing style shorthand to return camelCase
2024-02-13 10:06:28 -08:00
Nikhil Rao
f05d5ba7ba
Rename components in top level namespace (#2589) 2024-02-12 21:35:49 -08:00
Masen Furer
2b7e7450f8
Merge remote-tracking branch 'origin/main' into reflex-0.4.0 2024-02-12 12:22:50 -08:00
Masen Furer
3df4eac33d
test_call_script: update poll ending condition to avoid race (#2583) 2024-02-12 12:21:30 -08:00
Masen Furer
58b5e2f5bd
Merge remote-tracking branch 'origin/main' into reflex-0.4.0 2024-02-09 19:38:35 -08:00
Masen Furer
fe2778379d
Fix race condition in test_client_storage (#2568) 2024-02-09 16:15:07 -08:00