You are viewing a plain text version of this content. The canonical link for it is here.
Posted to github@beam.apache.org by "derrickaw (via GitHub)" <gi...@apache.org> on 2026/04/09 13:30:38 UTC
[PR] switch from js2py to quickjs [beam]
derrickaw opened a new pull request, #38130:
URL: https://github.com/apache/beam/pull/38130
**Please** add a meaningful description for your change here
------------------------
Thank you for your contribution! Follow this checklist to help us incorporate your contribution quickly and easily:
- [ ] Mention the appropriate issue in your description (for example: `addresses #123`), if applicable. This will automatically add a link to the pull request in the issue. If you would like the issue to automatically close on merging the pull request, comment `fixes #<ISSUE NUMBER>` instead.
- [ ] Update `CHANGES.md` with noteworthy changes.
- [ ] If this contribution is large, please file an Apache [Individual Contributor License Agreement](https://www.apache.org/licenses/icla.pdf).
See the [Contributor Guide](https://beam.apache.org/contribute) for more tips on [how to make review process smoother](https://github.com/apache/beam/blob/master/CONTRIBUTING.md#make-the-reviewers-job-easier).
To check the build health, please visit [https://github.com/apache/beam/blob/master/.test-infra/BUILD_STATUS.md](https://github.com/apache/beam/blob/master/.test-infra/BUILD_STATUS.md)
GitHub Actions Tests Status (on master branch)
------------------------------------------------------------------------------------------------
[](https://github.com/apache/beam/actions?query=workflow%3A%22Build+python+source+distribution+and+wheels%22+branch%3Amaster+event%3Aschedule)
[](https://github.com/apache/beam/actions?query=workflow%3A%22Python+Tests%22+branch%3Amaster+event%3Aschedule)
[](https://github.com/apache/beam/actions?query=workflow%3A%22Java+Tests%22+branch%3Amaster+event%3Aschedule)
[](https://github.com/apache/beam/actions?query=workflow%3A%22Go+tests%22+branch%3Amaster+event%3Aschedule)
See [CI.md](https://github.com/apache/beam/blob/master/CI.md) for more information about GitHub Actions CI or the [workflows README](https://github.com/apache/beam/blob/master/.github/workflows/README.md) to see a list of phrases to trigger workflows.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@beam.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] switch from js2py to quickjs [beam]
Posted by "derrickaw (via GitHub)" <gi...@apache.org>.
derrickaw commented on PR #38130:
URL: https://github.com/apache/beam/pull/38130#issuecomment-4245443417
Run Python PreCommit 3.11
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@beam.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] switch from js2py to quickjs [beam]
Posted by "gemini-code-assist[bot] (via GitHub)" <gi...@apache.org>.
gemini-code-assist[bot] commented on PR #38130:
URL: https://github.com/apache/beam/pull/38130#issuecomment-4214667968
## Summary of Changes
Hello, I'm Gemini Code Assist[^1]! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!
This pull request significantly updates the JavaScript User-Defined Function (UDF) execution within the Apache Beam Python SDK's YAML module. By migrating from the `js2py` library to `quickjs`, it resolves compatibility challenges with newer Python versions, particularly Python 3.12+, and establishes a more robust and maintainable foundation for running JavaScript logic. The changes involve a new callable wrapper and a JSON-based data interchange mechanism to facilitate seamless interaction between Python and JavaScript environments.
### Highlights
* **Dependency Switch**: Switched the JavaScript engine dependency from `js2py` to `quickjs` for YAML User-Defined Functions (UDFs).
* **Python 3.12+ Compatibility**: Addressed compatibility issues with Python 3.12 and later versions, as `js2py` had known limitations.
* **New Callable Wrapper**: Introduced a new `_QuickJsCallable` class to manage `quickjs` context, evaluate JavaScript code, and handle serialization for UDFs.
* **JSON-based Data Transfer**: Implemented JSON serialization and deserialization for data exchange between Python and JavaScript UDFs, ensuring robust data handling.
* **Updated UDF Execution Logic**: Refactored the `_expand_javascript_mapping_func` to utilize the `quickjs` engine and the new `_QuickJsCallable` for evaluating JavaScript expressions, callables, and file-based UDFs.
🧠**New Feature in Public Preview:** You can now enable **Memory** to help **Gemini Code Assist** learn from your team's feedback. This makes future code reviews more consistent and personalized to your project's style. **Click [here](https://codeassist.google/code-review/login) to enable Memory in your admin console.**
<details>
<summary><b>Using Gemini Code Assist</b></summary>
<br>
The full guide for Gemini Code Assist can be found on our [documentation page](https://developers.google.com/gemini-code-assist/docs/review-github-code), here are some quick tips.
<b>Invoking Gemini</b>
You can request assistance from Gemini at any point by creating a comment using either `/gemini <command>` or `@gemini-code-assist <command>`. Below is a summary of the supported commands on the current page.
Feature | Command | Description
--- | --- | ---
Code Review | `/gemini review` | Performs a code review for the current pull request in its current state.
Pull Request Summary | `/gemini summary` | Provides a summary of the current pull request in its current state.
Comment | @gemini-code-assist | Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help | `/gemini help` | Displays a list of available commands.
<b>Customization</b>
To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a `.gemini/` folder in the base of the repository. Detailed instructions can be found [here](https://developers.google.com/gemini-code-assist/docs/customize-gemini-behavior-github).
<b>Limitations & Feedback</b>
Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with :thumbsup: and :thumbsdown: on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for GitHub and other Google products, sign up [here](https://google.qualtrics.com/jfe/form/SV_2cyuGuTWsEw84yG).
</details>
[^1]: Review the [Privacy Notices](https://policies.google.com/privacy), [Generative AI Prohibited Use Policy](https://policies.google.com/terms/generative-ai/use-policy), [Terms of Service](https://policies.google.com/terms), and learn how to configure Gemini Code Assist in GitHub [here](https://developers.google.com/gemini-code-assist/docs/customize-gemini-behavior-github). Gemini can make mistakes, so double check it and [use code with caution](https://support.google.com/legal/answer/13505487).
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@beam.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] switch from js2py to quickjs [beam]
Posted by "derrickaw (via GitHub)" <gi...@apache.org>.
derrickaw commented on code in PR #38130:
URL: https://github.com/apache/beam/pull/38130#discussion_r3093146314
##########
sdks/python/apache_beam/yaml/yaml_mapping.py:
##########
@@ -178,18 +177,34 @@ def _check_mapping_arguments(
raise ValueError(f'{transform_name} cannot specify "name" without "path"')
-# js2py's JsObjectWrapper object has a self-referencing __dict__ property
-# that cannot be pickled without implementing the __getstate__ and
-# __setstate__ methods.
-class _CustomJsObjectWrapper(JsObjectWrapper):
- def __init__(self, js_obj):
- super().__init__(js_obj.__dict__['_obj'])
+class _QuickJsCallable:
+ def __init__(self, source, name=None):
+ self.source = source
+ self.name = name
+ self._func = None
+
+ def _get_func(self):
+ if self._func is None:
+ if quickjs is None:
+ raise ValueError("quickjs is not installed.")
+ context = quickjs.Context()
+ if self.name:
+ context.eval(self.source)
+ self._func = context.get(self.name)
+ else:
+ self._func = context.eval(self.source)
+ return self._func
+
+ def __call__(self, *args, **kwargs):
+ return self._get_func()(*args, **kwargs)
Review Comment:
done
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@beam.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] switch from js2py to quickjs [beam]
Posted by "derrickaw (via GitHub)" <gi...@apache.org>.
derrickaw commented on PR #38130:
URL: https://github.com/apache/beam/pull/38130#issuecomment-4245988518
Run PythonDocker PreCommit 3.10
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@beam.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] switch from js2py to quickjs [beam]
Posted by "derrickaw (via GitHub)" <gi...@apache.org>.
derrickaw commented on PR #38130:
URL: https://github.com/apache/beam/pull/38130#issuecomment-4243705120
Run Python PreCommit 3.14
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@beam.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] switch from js2py to quickjs [beam]
Posted by "derrickaw (via GitHub)" <gi...@apache.org>.
derrickaw commented on PR #38130:
URL: https://github.com/apache/beam/pull/38130#issuecomment-4237867425
Run Python PreCommit 3.14
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@beam.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] switch from js2py to quickjs [beam]
Posted by "derrickaw (via GitHub)" <gi...@apache.org>.
derrickaw commented on PR #38130:
URL: https://github.com/apache/beam/pull/38130#issuecomment-4261513355
(Run Python PreCommit 3.10
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@beam.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] switch from js2py to quickjs [beam]
Posted by "derrickaw (via GitHub)" <gi...@apache.org>.
derrickaw commented on PR #38130:
URL: https://github.com/apache/beam/pull/38130#issuecomment-4243706924
Run Python_ML PreCommit 3.10
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@beam.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] switch from js2py to quickjs [beam]
Posted by "derrickaw (via GitHub)" <gi...@apache.org>.
derrickaw commented on PR #38130:
URL: https://github.com/apache/beam/pull/38130#issuecomment-4248459027
Run PythonDocker PreCommit 3.13
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@beam.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] switch from js2py to quickjs [beam]
Posted by "derrickaw (via GitHub)" <gi...@apache.org>.
derrickaw commented on code in PR #38130:
URL: https://github.com/apache/beam/pull/38130#discussion_r3086145060
##########
sdks/python/apache_beam/yaml/yaml_mapping.py:
##########
@@ -210,78 +224,49 @@ def py_value_to_js_dict(py_value):
def _expand_javascript_mapping_func(
original_fields, expression=None, callable=None, path=None, name=None):
- # Check for installed js2py package
- if js2py is None:
+ # Check for installed quickjs package
+ if quickjs is None:
raise ValueError(
- "Javascript mapping functions are not supported on"
- " Python 3.12 or later.")
-
- # import remaining js2py objects
- from js2py import base
- from js2py.constructors import jsdate
- from js2py.internals import simplex
-
- js_array_type = (
- base.PyJsArray,
- base.PyJsArrayBuffer,
- base.PyJsInt8Array,
- base.PyJsUint8Array,
- base.PyJsUint8ClampedArray,
- base.PyJsInt16Array,
- base.PyJsUint16Array,
- base.PyJsInt32Array,
- base.PyJsUint32Array,
- base.PyJsFloat32Array,
- base.PyJsFloat64Array)
-
- def _js_object_to_py_object(obj):
- if isinstance(obj, (base.PyJsNumber, base.PyJsString, base.PyJsBoolean)):
- return base.to_python(obj)
- elif isinstance(obj, js_array_type):
- return [_js_object_to_py_object(value) for value in obj.to_list()]
- elif isinstance(obj, jsdate.PyJsDate):
- return obj.to_utc_dt()
- elif isinstance(obj, (base.PyJsNull, base.PyJsUndefined)):
- return None
- elif isinstance(obj, base.PyJsError):
- raise RuntimeError(obj['message'])
- elif isinstance(obj, base.PyJsObject):
- return {
- key: _js_object_to_py_object(value['value'])
- for (key, value) in obj.own.items()
- }
- elif isinstance(obj, base.JsObjectWrapper):
- return _js_object_to_py_object(obj._obj)
+ "Javascript mapping functions require the 'quickjs' package.")
- return obj
+ import json
if expression:
- source = '\n'.join(['function(__row__) {'] + [
- f' {name} = __row__.{name}'
- for name in original_fields if name in expression
- ] + [' return (' + expression + ')'] + ['}'])
- js_func = _CustomJsObjectWrapper(js2py.eval_js(source))
+ source = '\n'.join(
+ ['function fn(json_row) {', ' const __row__ = JSON.parse(json_row);'] +
+ [
+ f' const {name} = __row__.{name};'
+ for name in original_fields if name in expression
+ ] + [' return JSON.stringify(' + expression + ');'] + ['}'])
+ js_func = _QuickJsCallable(source, "fn")
Review Comment:
done
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@beam.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] switch from js2py to quickjs [beam]
Posted by "derrickaw (via GitHub)" <gi...@apache.org>.
derrickaw commented on PR #38130:
URL: https://github.com/apache/beam/pull/38130#issuecomment-4253919766
Run Python PreCommit 3.10
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@beam.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] switch from js2py to quickjs [beam]
Posted by "derrickaw (via GitHub)" <gi...@apache.org>.
derrickaw commented on code in PR #38130:
URL: https://github.com/apache/beam/pull/38130#discussion_r3093069271
##########
sdks/python/apache_beam/yaml/yaml_mapping.py:
##########
@@ -210,78 +225,106 @@ def py_value_to_js_dict(py_value):
def _expand_javascript_mapping_func(
original_fields, expression=None, callable=None, path=None, name=None):
- # Check for installed js2py package
- if js2py is None:
+ # Check for installed quickjs package
+ if quickjs is None:
raise ValueError(
- "Javascript mapping functions are not supported on"
- " Python 3.12 or later.")
-
- # import remaining js2py objects
- from js2py import base
- from js2py.constructors import jsdate
- from js2py.internals import simplex
-
- js_array_type = (
- base.PyJsArray,
- base.PyJsArrayBuffer,
- base.PyJsInt8Array,
- base.PyJsUint8Array,
- base.PyJsUint8ClampedArray,
- base.PyJsInt16Array,
- base.PyJsUint16Array,
- base.PyJsInt32Array,
- base.PyJsUint32Array,
- base.PyJsFloat32Array,
- base.PyJsFloat64Array)
-
- def _js_object_to_py_object(obj):
- if isinstance(obj, (base.PyJsNumber, base.PyJsString, base.PyJsBoolean)):
- return base.to_python(obj)
- elif isinstance(obj, js_array_type):
- return [_js_object_to_py_object(value) for value in obj.to_list()]
- elif isinstance(obj, jsdate.PyJsDate):
- return obj.to_utc_dt()
- elif isinstance(obj, (base.PyJsNull, base.PyJsUndefined)):
- return None
- elif isinstance(obj, base.PyJsError):
- raise RuntimeError(obj['message'])
- elif isinstance(obj, base.PyJsObject):
- return {
- key: _js_object_to_py_object(value['value'])
- for (key, value) in obj.own.items()
- }
- elif isinstance(obj, base.JsObjectWrapper):
- return _js_object_to_py_object(obj._obj)
+ "Javascript mapping functions require the 'quickjs' package.")
- return obj
+ def make_bridge_source(func_name, call_expr):
+ keys_json = json.dumps(list(original_fields))
+ return (
+ f"function {func_name}(serialized_flags, ...values) {{ "
+ f" const keys = JSON.parse('{keys_json}'); "
Review Comment:
done
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@beam.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] switch from js2py to quickjs [beam]
Posted by "derrickaw (via GitHub)" <gi...@apache.org>.
derrickaw commented on PR #38130:
URL: https://github.com/apache/beam/pull/38130#issuecomment-4248176233
Run PythonDocker PreCommit 3.14
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@beam.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] switch from js2py to quickjs [beam]
Posted by "derrickaw (via GitHub)" <gi...@apache.org>.
derrickaw commented on PR #38130:
URL: https://github.com/apache/beam/pull/38130#issuecomment-4260673660
Run Python PreCommit 3.10
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@beam.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] switch from js2py to quickjs [beam]
Posted by "derrickaw (via GitHub)" <gi...@apache.org>.
derrickaw commented on PR #38130:
URL: https://github.com/apache/beam/pull/38130#issuecomment-4261111519
Run Python PreCommit 3.11
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@beam.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] switch from js2py to quickjs [beam]
Posted by "derrickaw (via GitHub)" <gi...@apache.org>.
derrickaw commented on code in PR #38130:
URL: https://github.com/apache/beam/pull/38130#discussion_r3086147573
##########
sdks/python/apache_beam/yaml/yaml_mapping.py:
##########
@@ -210,78 +224,49 @@ def py_value_to_js_dict(py_value):
def _expand_javascript_mapping_func(
original_fields, expression=None, callable=None, path=None, name=None):
- # Check for installed js2py package
- if js2py is None:
+ # Check for installed quickjs package
+ if quickjs is None:
raise ValueError(
- "Javascript mapping functions are not supported on"
- " Python 3.12 or later.")
-
- # import remaining js2py objects
- from js2py import base
- from js2py.constructors import jsdate
- from js2py.internals import simplex
-
- js_array_type = (
- base.PyJsArray,
- base.PyJsArrayBuffer,
- base.PyJsInt8Array,
- base.PyJsUint8Array,
- base.PyJsUint8ClampedArray,
- base.PyJsInt16Array,
- base.PyJsUint16Array,
- base.PyJsInt32Array,
- base.PyJsUint32Array,
- base.PyJsFloat32Array,
- base.PyJsFloat64Array)
-
- def _js_object_to_py_object(obj):
- if isinstance(obj, (base.PyJsNumber, base.PyJsString, base.PyJsBoolean)):
- return base.to_python(obj)
- elif isinstance(obj, js_array_type):
- return [_js_object_to_py_object(value) for value in obj.to_list()]
- elif isinstance(obj, jsdate.PyJsDate):
- return obj.to_utc_dt()
- elif isinstance(obj, (base.PyJsNull, base.PyJsUndefined)):
- return None
- elif isinstance(obj, base.PyJsError):
- raise RuntimeError(obj['message'])
- elif isinstance(obj, base.PyJsObject):
- return {
- key: _js_object_to_py_object(value['value'])
- for (key, value) in obj.own.items()
- }
- elif isinstance(obj, base.JsObjectWrapper):
- return _js_object_to_py_object(obj._obj)
+ "Javascript mapping functions require the 'quickjs' package.")
- return obj
+ import json
if expression:
- source = '\n'.join(['function(__row__) {'] + [
- f' {name} = __row__.{name}'
- for name in original_fields if name in expression
- ] + [' return (' + expression + ')'] + ['}'])
- js_func = _CustomJsObjectWrapper(js2py.eval_js(source))
+ source = '\n'.join(
+ ['function fn(json_row) {', ' const __row__ = JSON.parse(json_row);'] +
+ [
+ f' const {name} = __row__.{name};'
+ for name in original_fields if name in expression
+ ] + [' return JSON.stringify(' + expression + ');'] + ['}'])
+ js_func = _QuickJsCallable(source, "fn")
elif callable:
- js_func = _CustomJsObjectWrapper(js2py.eval_js(callable))
+ # Wrap the callable in a named function to use quickjs.Function
+ source = (
+ f"function fn(json_row) {{ "
+ f"const row = JSON.parse(json_row); "
+ f"return JSON.stringify(({callable})(row)); }}")
+ js_func = _QuickJsCallable(source, "fn")
else:
if not path.endswith('.js'):
raise ValueError(f'File "{path}" is not a valid .js file.')
udf_code = FileSystems.open(path).read().decode()
- js = js2py.EvalJs()
- js.eval(udf_code)
- js_func = _CustomJsObjectWrapper(getattr(js, name))
+ bridge_source = (
+ udf_code + f"\nfunction bridge_fn(json_row) {{ "
+ f"return JSON.stringify({name}(JSON.parse(json_row))); }}")
+ js_func = _QuickJsCallable(bridge_source, "bridge_fn")
def js_wrapper(row):
row_as_dict = py_value_to_js_dict(row)
+ row_json = json.dumps(row_as_dict)
try:
- js_result = js_func(row_as_dict)
- except simplex.JsException as exn:
+ js_result_json = js_func(row_json)
+ js_result = json.loads(js_result_json)
Review Comment:
done
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@beam.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] switch from js2py to quickjs [beam]
Posted by "derrickaw (via GitHub)" <gi...@apache.org>.
derrickaw commented on PR #38130:
URL: https://github.com/apache/beam/pull/38130#issuecomment-4254002703
Run Python_Examples PreCommit 3.13
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@beam.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] switch from js2py to quickjs [beam]
Posted by "derrickaw (via GitHub)" <gi...@apache.org>.
derrickaw commented on PR #38130:
URL: https://github.com/apache/beam/pull/38130#issuecomment-4253921272
Run Python_Dataframes PreCommit 3.14
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@beam.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] switch from js2py to quickjs [beam]
Posted by "derrickaw (via GitHub)" <gi...@apache.org>.
derrickaw commented on PR #38130:
URL: https://github.com/apache/beam/pull/38130#issuecomment-4254219496
Run Python PreCommit 3.10
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@beam.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] switch from js2py to quickjs [beam]
Posted by "derrickaw (via GitHub)" <gi...@apache.org>.
derrickaw commented on PR #38130:
URL: https://github.com/apache/beam/pull/38130#issuecomment-4239547525
Run Python_Examples PreCommit 3.11
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@beam.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] switch from js2py to quickjs [beam]
Posted by "derrickaw (via GitHub)" <gi...@apache.org>.
derrickaw commented on code in PR #38130:
URL: https://github.com/apache/beam/pull/38130#discussion_r3093139291
##########
sdks/python/apache_beam/yaml/yaml_mapping.py:
##########
@@ -210,78 +225,106 @@ def py_value_to_js_dict(py_value):
def _expand_javascript_mapping_func(
original_fields, expression=None, callable=None, path=None, name=None):
- # Check for installed js2py package
- if js2py is None:
+ # Check for installed quickjs package
+ if quickjs is None:
raise ValueError(
- "Javascript mapping functions are not supported on"
- " Python 3.12 or later.")
-
- # import remaining js2py objects
- from js2py import base
- from js2py.constructors import jsdate
- from js2py.internals import simplex
-
- js_array_type = (
- base.PyJsArray,
- base.PyJsArrayBuffer,
- base.PyJsInt8Array,
- base.PyJsUint8Array,
- base.PyJsUint8ClampedArray,
- base.PyJsInt16Array,
- base.PyJsUint16Array,
- base.PyJsInt32Array,
- base.PyJsUint32Array,
- base.PyJsFloat32Array,
- base.PyJsFloat64Array)
-
- def _js_object_to_py_object(obj):
- if isinstance(obj, (base.PyJsNumber, base.PyJsString, base.PyJsBoolean)):
- return base.to_python(obj)
- elif isinstance(obj, js_array_type):
- return [_js_object_to_py_object(value) for value in obj.to_list()]
- elif isinstance(obj, jsdate.PyJsDate):
- return obj.to_utc_dt()
- elif isinstance(obj, (base.PyJsNull, base.PyJsUndefined)):
- return None
- elif isinstance(obj, base.PyJsError):
- raise RuntimeError(obj['message'])
- elif isinstance(obj, base.PyJsObject):
- return {
- key: _js_object_to_py_object(value['value'])
- for (key, value) in obj.own.items()
- }
- elif isinstance(obj, base.JsObjectWrapper):
- return _js_object_to_py_object(obj._obj)
+ "Javascript mapping functions require the 'quickjs' package.")
- return obj
+ def make_bridge_source(func_name, call_expr):
+ keys_json = json.dumps(list(original_fields))
+ return (
+ f"function {func_name}(serialized_flags, ...values) {{ "
+ f" const keys = JSON.parse('{keys_json}'); "
+ f" const flags = serialized_flags.split(','); "
+ f" const row = {{}}; "
+ f" for (let i = 0; i < keys.length; i++) {{ "
+ f" let val = values[i]; "
+ f" if (flags[i] === '1') val = JSON.parse(val); "
+ f" row[keys[i]] = val; "
+ f" }} "
+ f" const result = {call_expr}; "
+ f" return (typeof result === 'object' && result !== null) "
+ f"? '__json__:' + JSON.stringify(result) : result; "
Review Comment:
good point, done
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@beam.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] switch from js2py to quickjs [beam]
Posted by "derrickaw (via GitHub)" <gi...@apache.org>.
derrickaw commented on code in PR #38130:
URL: https://github.com/apache/beam/pull/38130#discussion_r3093344888
##########
sdks/python/apache_beam/yaml/yaml_mapping.py:
##########
@@ -17,6 +17,7 @@
"""This module defines the basic MapToFields operation."""
import itertools
+import json
Review Comment:
done
##########
sdks/python/apache_beam/yaml/yaml_mapping.py:
##########
@@ -210,78 +225,109 @@ def py_value_to_js_dict(py_value):
def _expand_javascript_mapping_func(
original_fields, expression=None, callable=None, path=None, name=None):
- # Check for installed js2py package
- if js2py is None:
+ # Check for installed quickjs package
+ if quickjs is None:
raise ValueError(
- "Javascript mapping functions are not supported on"
- " Python 3.12 or later.")
-
- # import remaining js2py objects
- from js2py import base
- from js2py.constructors import jsdate
- from js2py.internals import simplex
-
- js_array_type = (
- base.PyJsArray,
- base.PyJsArrayBuffer,
- base.PyJsInt8Array,
- base.PyJsUint8Array,
- base.PyJsUint8ClampedArray,
- base.PyJsInt16Array,
- base.PyJsUint16Array,
- base.PyJsInt32Array,
- base.PyJsUint32Array,
- base.PyJsFloat32Array,
- base.PyJsFloat64Array)
-
- def _js_object_to_py_object(obj):
- if isinstance(obj, (base.PyJsNumber, base.PyJsString, base.PyJsBoolean)):
- return base.to_python(obj)
- elif isinstance(obj, js_array_type):
- return [_js_object_to_py_object(value) for value in obj.to_list()]
- elif isinstance(obj, jsdate.PyJsDate):
- return obj.to_utc_dt()
- elif isinstance(obj, (base.PyJsNull, base.PyJsUndefined)):
- return None
- elif isinstance(obj, base.PyJsError):
- raise RuntimeError(obj['message'])
- elif isinstance(obj, base.PyJsObject):
- return {
- key: _js_object_to_py_object(value['value'])
- for (key, value) in obj.own.items()
- }
- elif isinstance(obj, base.JsObjectWrapper):
- return _js_object_to_py_object(obj._obj)
-
- return obj
+ "Javascript mapping functions require the 'quickjs' package.")
+
+ def make_bridge_source(func_name, call_expr):
+ # The bridge function facilitates high-performance data transfer from Python
+ # to QuickJS by reconstructing the row object in JS.
+ # To minimize JSON overhead, primitives are passed directly, while complex
+ # types (lists/dicts) are passed as JSON strings and parsed in JS.
+ # The 'flags' argument indicates which values need parsing.
+ keys_json = json.dumps(list(original_fields))
+ return (
+ f"function {func_name}(serialized_flags, ...values) {{ "
+ f" const keys = {keys_json}; "
+ f" const flags = serialized_flags.split(','); "
+ f" const row = {{}}; "
+ f" for (let i = 0; i < keys.length; i++) {{ "
+ f" let val = values[i]; "
+ f" if (flags[i] === '1') val = JSON.parse(val); "
+ f" row[keys[i]] = val; "
+ f" }} "
+ f" const result = {call_expr}; "
+ f" if (result instanceof Date) "
+ f"return {{__type__: 'date', value: result.toISOString()}}; "
+ f" return result; "
+ f"}}")
if expression:
- source = '\n'.join(['function(__row__) {'] + [
- f' {name} = __row__.{name}'
- for name in original_fields if name in expression
- ] + [' return (' + expression + ')'] + ['}'])
- js_func = _CustomJsObjectWrapper(js2py.eval_js(source))
+ args = [
+ name for name in original_fields
+ if name.isidentifier() and name in expression
+ ]
+ parses = []
+ for i, arg in enumerate(args):
+ parses.append(f" if (flags[{i}] === '1') {arg} = JSON.parse({arg});")
+
+ source = f"""
+function fn(serialized_flags, {", ".join(args)}) {{
+ const flags = serialized_flags.split(',');
+{chr(10).join(parses)}
+ const result = ({expression});
+ if (result instanceof Date) return {{__type__: 'date', value: result.toISOString()}};
+ return result;
+}}
+"""
+ js_func = _QuickJsCallable(source, "fn")
+ used_fields = args
elif callable:
- js_func = _CustomJsObjectWrapper(js2py.eval_js(callable))
+ source = make_bridge_source("fn", f"({callable})(row)")
+ js_func = _QuickJsCallable(source, "fn")
+ used_fields = None
else:
if not path.endswith('.js'):
raise ValueError(f'File "{path}" is not a valid .js file.')
udf_code = FileSystems.open(path).read().decode()
- js = js2py.EvalJs()
- js.eval(udf_code)
- js_func = _CustomJsObjectWrapper(getattr(js, name))
+ bridge_source = udf_code + "\n" + make_bridge_source(
+ "bridge_fn", f"{name}(row)")
+ js_func = _QuickJsCallable(bridge_source, "bridge_fn")
+ used_fields = None
+
+ def _prepare_args(vals):
+ js_vals = []
+ flags = []
+ for val in vals:
+ if isinstance(val, (list, dict)):
+ js_vals.append(json.dumps(val))
+ flags.append('1')
+ else:
+ js_vals.append(val)
+ flags.append('0')
+ return ",".join(flags), js_vals
def js_wrapper(row):
- row_as_dict = py_value_to_js_dict(row)
+ # Prepare arguments for the JS function. We optimize performance by
+ # passing primitives directly and only serializing complex types (lists,
+ # dicts) to JSON strings. A string of flags ('0' or '1') is passed to
+ # inform the JS bridge which arguments need to be JSON.parsed.
+ if expression:
+ vals = [py_value_to_js_dict(getattr(row, name)) for name in used_fields]
+ else:
+ row_as_dict = py_value_to_js_dict(row)
+ vals = [row_as_dict.get(name) for name in original_fields]
+
+ flags_str, js_vals = _prepare_args(vals)
+
try:
- js_result = js_func(row_as_dict)
- except simplex.JsException as exn:
+ js_result = js_func(flags_str, *js_vals)
+ except Exception as exn:
raise RuntimeError(
- f"Error evaluating javascript expression: "
- f"{exn.mes['message']}") from exn
- return dicts_to_rows(_js_object_to_py_object(js_result))
+ f"Error evaluating javascript expression: {exn}") from exn
+
+ if isinstance(js_result, quickjs.Object):
+ obj = json.loads(js_result.json())
+ if isinstance(obj, dict) and obj.get('__type__') == 'date':
+ import datetime
+ js_result = datetime.datetime.fromisoformat(obj['value'])
Review Comment:
done
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@beam.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] switch from js2py to quickjs [beam]
Posted by "derrickaw (via GitHub)" <gi...@apache.org>.
derrickaw commented on PR #38130:
URL: https://github.com/apache/beam/pull/38130#issuecomment-4237969771
Run Python PreCommit 3.11
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@beam.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] switch from js2py to quickjs [beam]
Posted by "derrickaw (via GitHub)" <gi...@apache.org>.
derrickaw commented on PR #38130:
URL: https://github.com/apache/beam/pull/38130#issuecomment-4268644714
Run Python PreCommit 3.10
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@beam.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] switch from js2py to quickjs [beam]
Posted by "derrickaw (via GitHub)" <gi...@apache.org>.
derrickaw commented on PR #38130:
URL: https://github.com/apache/beam/pull/38130#issuecomment-4245103610
Run Python_Transforms PreCommit 3.10
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@beam.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] switch from js2py to quickjs [beam]
Posted by "gemini-code-assist[bot] (via GitHub)" <gi...@apache.org>.
gemini-code-assist[bot] commented on code in PR #38130:
URL: https://github.com/apache/beam/pull/38130#discussion_r3083410525
##########
sdks/python/apache_beam/yaml/yaml_mapping.py:
##########
@@ -210,78 +224,49 @@ def py_value_to_js_dict(py_value):
def _expand_javascript_mapping_func(
original_fields, expression=None, callable=None, path=None, name=None):
- # Check for installed js2py package
- if js2py is None:
+ # Check for installed quickjs package
+ if quickjs is None:
raise ValueError(
- "Javascript mapping functions are not supported on"
- " Python 3.12 or later.")
-
- # import remaining js2py objects
- from js2py import base
- from js2py.constructors import jsdate
- from js2py.internals import simplex
-
- js_array_type = (
- base.PyJsArray,
- base.PyJsArrayBuffer,
- base.PyJsInt8Array,
- base.PyJsUint8Array,
- base.PyJsUint8ClampedArray,
- base.PyJsInt16Array,
- base.PyJsUint16Array,
- base.PyJsInt32Array,
- base.PyJsUint32Array,
- base.PyJsFloat32Array,
- base.PyJsFloat64Array)
-
- def _js_object_to_py_object(obj):
- if isinstance(obj, (base.PyJsNumber, base.PyJsString, base.PyJsBoolean)):
- return base.to_python(obj)
- elif isinstance(obj, js_array_type):
- return [_js_object_to_py_object(value) for value in obj.to_list()]
- elif isinstance(obj, jsdate.PyJsDate):
- return obj.to_utc_dt()
- elif isinstance(obj, (base.PyJsNull, base.PyJsUndefined)):
- return None
- elif isinstance(obj, base.PyJsError):
- raise RuntimeError(obj['message'])
- elif isinstance(obj, base.PyJsObject):
- return {
- key: _js_object_to_py_object(value['value'])
- for (key, value) in obj.own.items()
- }
- elif isinstance(obj, base.JsObjectWrapper):
- return _js_object_to_py_object(obj._obj)
+ "Javascript mapping functions require the 'quickjs' package.")
- return obj
+ import json
if expression:
- source = '\n'.join(['function(__row__) {'] + [
- f' {name} = __row__.{name}'
- for name in original_fields if name in expression
- ] + [' return (' + expression + ')'] + ['}'])
- js_func = _CustomJsObjectWrapper(js2py.eval_js(source))
+ source = '\n'.join(
+ ['function fn(json_row) {', ' const __row__ = JSON.parse(json_row);'] +
+ [
+ f' const {name} = __row__.{name};'
+ for name in original_fields if name in expression
+ ] + [' return JSON.stringify(' + expression + ');'] + ['}'])
+ js_func = _QuickJsCallable(source, "fn")
elif callable:
- js_func = _CustomJsObjectWrapper(js2py.eval_js(callable))
+ # Wrap the callable in a named function to use quickjs.Function
+ source = (
+ f"function fn(json_row) {{ "
+ f"const row = JSON.parse(json_row); "
+ f"return JSON.stringify(({callable})(row)); }}")
+ js_func = _QuickJsCallable(source, "fn")
else:
if not path.endswith('.js'):
raise ValueError(f'File "{path}" is not a valid .js file.')
udf_code = FileSystems.open(path).read().decode()
- js = js2py.EvalJs()
- js.eval(udf_code)
- js_func = _CustomJsObjectWrapper(getattr(js, name))
+ bridge_source = (
+ udf_code + f"\nfunction bridge_fn(json_row) {{ "
+ f"return JSON.stringify({name}(JSON.parse(json_row))); }}")
+ js_func = _QuickJsCallable(bridge_source, "bridge_fn")
Review Comment:

Manual JSON serialization in the bridge function is unnecessary. Passing the object directly is more efficient.
```python
bridge_source = (
udf_code + f"\nfunction bridge_fn(row) {{ "
f"return {name}(row); }}")
js_func = _QuickJsCallable(bridge_source, "bridge_fn")
```
##########
sdks/python/apache_beam/yaml/yaml_mapping.py:
##########
@@ -210,78 +224,49 @@ def py_value_to_js_dict(py_value):
def _expand_javascript_mapping_func(
original_fields, expression=None, callable=None, path=None, name=None):
- # Check for installed js2py package
- if js2py is None:
+ # Check for installed quickjs package
+ if quickjs is None:
raise ValueError(
- "Javascript mapping functions are not supported on"
- " Python 3.12 or later.")
-
- # import remaining js2py objects
- from js2py import base
- from js2py.constructors import jsdate
- from js2py.internals import simplex
-
- js_array_type = (
- base.PyJsArray,
- base.PyJsArrayBuffer,
- base.PyJsInt8Array,
- base.PyJsUint8Array,
- base.PyJsUint8ClampedArray,
- base.PyJsInt16Array,
- base.PyJsUint16Array,
- base.PyJsInt32Array,
- base.PyJsUint32Array,
- base.PyJsFloat32Array,
- base.PyJsFloat64Array)
-
- def _js_object_to_py_object(obj):
- if isinstance(obj, (base.PyJsNumber, base.PyJsString, base.PyJsBoolean)):
- return base.to_python(obj)
- elif isinstance(obj, js_array_type):
- return [_js_object_to_py_object(value) for value in obj.to_list()]
- elif isinstance(obj, jsdate.PyJsDate):
- return obj.to_utc_dt()
- elif isinstance(obj, (base.PyJsNull, base.PyJsUndefined)):
- return None
- elif isinstance(obj, base.PyJsError):
- raise RuntimeError(obj['message'])
- elif isinstance(obj, base.PyJsObject):
- return {
- key: _js_object_to_py_object(value['value'])
- for (key, value) in obj.own.items()
- }
- elif isinstance(obj, base.JsObjectWrapper):
- return _js_object_to_py_object(obj._obj)
+ "Javascript mapping functions require the 'quickjs' package.")
- return obj
+ import json
if expression:
- source = '\n'.join(['function(__row__) {'] + [
- f' {name} = __row__.{name}'
- for name in original_fields if name in expression
- ] + [' return (' + expression + ')'] + ['}'])
- js_func = _CustomJsObjectWrapper(js2py.eval_js(source))
+ source = '\n'.join(
+ ['function fn(json_row) {', ' const __row__ = JSON.parse(json_row);'] +
+ [
+ f' const {name} = __row__.{name};'
+ for name in original_fields if name in expression
+ ] + [' return JSON.stringify(' + expression + ');'] + ['}'])
+ js_func = _QuickJsCallable(source, "fn")
elif callable:
- js_func = _CustomJsObjectWrapper(js2py.eval_js(callable))
+ # Wrap the callable in a named function to use quickjs.Function
+ source = (
+ f"function fn(json_row) {{ "
+ f"const row = JSON.parse(json_row); "
+ f"return JSON.stringify(({callable})(row)); }}")
+ js_func = _QuickJsCallable(source, "fn")
else:
if not path.endswith('.js'):
raise ValueError(f'File "{path}" is not a valid .js file.')
udf_code = FileSystems.open(path).read().decode()
- js = js2py.EvalJs()
- js.eval(udf_code)
- js_func = _CustomJsObjectWrapper(getattr(js, name))
+ bridge_source = (
+ udf_code + f"\nfunction bridge_fn(json_row) {{ "
+ f"return JSON.stringify({name}(JSON.parse(json_row))); }}")
+ js_func = _QuickJsCallable(bridge_source, "bridge_fn")
def js_wrapper(row):
row_as_dict = py_value_to_js_dict(row)
+ row_json = json.dumps(row_as_dict)
try:
- js_result = js_func(row_as_dict)
- except simplex.JsException as exn:
+ js_result_json = js_func(row_json)
+ js_result = json.loads(js_result_json)
Review Comment:

By removing the manual JSON serialization in the JavaScript source, you can pass the dictionary directly to the `js_func` and receive a Python object back, avoiding the overhead of `json.dumps` and `json.loads`.
```suggestion
try:
js_result = js_func(row_as_dict)
except Exception as exn:
```
##########
sdks/python/apache_beam/yaml/yaml_mapping.py:
##########
@@ -210,78 +224,49 @@ def py_value_to_js_dict(py_value):
def _expand_javascript_mapping_func(
original_fields, expression=None, callable=None, path=None, name=None):
- # Check for installed js2py package
- if js2py is None:
+ # Check for installed quickjs package
+ if quickjs is None:
raise ValueError(
- "Javascript mapping functions are not supported on"
- " Python 3.12 or later.")
-
- # import remaining js2py objects
- from js2py import base
- from js2py.constructors import jsdate
- from js2py.internals import simplex
-
- js_array_type = (
- base.PyJsArray,
- base.PyJsArrayBuffer,
- base.PyJsInt8Array,
- base.PyJsUint8Array,
- base.PyJsUint8ClampedArray,
- base.PyJsInt16Array,
- base.PyJsUint16Array,
- base.PyJsInt32Array,
- base.PyJsUint32Array,
- base.PyJsFloat32Array,
- base.PyJsFloat64Array)
-
- def _js_object_to_py_object(obj):
- if isinstance(obj, (base.PyJsNumber, base.PyJsString, base.PyJsBoolean)):
- return base.to_python(obj)
- elif isinstance(obj, js_array_type):
- return [_js_object_to_py_object(value) for value in obj.to_list()]
- elif isinstance(obj, jsdate.PyJsDate):
- return obj.to_utc_dt()
- elif isinstance(obj, (base.PyJsNull, base.PyJsUndefined)):
- return None
- elif isinstance(obj, base.PyJsError):
- raise RuntimeError(obj['message'])
- elif isinstance(obj, base.PyJsObject):
- return {
- key: _js_object_to_py_object(value['value'])
- for (key, value) in obj.own.items()
- }
- elif isinstance(obj, base.JsObjectWrapper):
- return _js_object_to_py_object(obj._obj)
+ "Javascript mapping functions require the 'quickjs' package.")
- return obj
+ import json
if expression:
- source = '\n'.join(['function(__row__) {'] + [
- f' {name} = __row__.{name}'
- for name in original_fields if name in expression
- ] + [' return (' + expression + ')'] + ['}'])
- js_func = _CustomJsObjectWrapper(js2py.eval_js(source))
+ source = '\n'.join(
+ ['function fn(json_row) {', ' const __row__ = JSON.parse(json_row);'] +
+ [
+ f' const {name} = __row__.{name};'
+ for name in original_fields if name in expression
+ ] + [' return JSON.stringify(' + expression + ');'] + ['}'])
+ js_func = _QuickJsCallable(source, "fn")
Review Comment:

The use of `JSON.parse` and `JSON.stringify` inside the JavaScript code, combined with `json.dumps` and `json.loads` in Python, introduces significant overhead for every row processed. The `quickjs` library supports direct conversion between Python dictionaries/lists and JavaScript objects. Removing this manual serialization will improve performance and robustness (e.g., handling of `NaN` or `Infinity` which are not standard JSON). Additionally, using bracket notation for field access is safer for field names that might contain special characters.
```python
if expression:
source = '\n'.join(
['function fn(__row__) {'] +
[
f' const {name} = __row__["{name}"];'
for name in original_fields if name.isidentifier() and name in expression
] + [' return (' + expression + ');'] + ['}'])
js_func = _QuickJsCallable(source, "fn")
```
##########
sdks/python/apache_beam/yaml/yaml_mapping.py:
##########
@@ -210,78 +224,49 @@ def py_value_to_js_dict(py_value):
def _expand_javascript_mapping_func(
original_fields, expression=None, callable=None, path=None, name=None):
- # Check for installed js2py package
- if js2py is None:
+ # Check for installed quickjs package
+ if quickjs is None:
raise ValueError(
- "Javascript mapping functions are not supported on"
- " Python 3.12 or later.")
-
- # import remaining js2py objects
- from js2py import base
- from js2py.constructors import jsdate
- from js2py.internals import simplex
-
- js_array_type = (
- base.PyJsArray,
- base.PyJsArrayBuffer,
- base.PyJsInt8Array,
- base.PyJsUint8Array,
- base.PyJsUint8ClampedArray,
- base.PyJsInt16Array,
- base.PyJsUint16Array,
- base.PyJsInt32Array,
- base.PyJsUint32Array,
- base.PyJsFloat32Array,
- base.PyJsFloat64Array)
-
- def _js_object_to_py_object(obj):
- if isinstance(obj, (base.PyJsNumber, base.PyJsString, base.PyJsBoolean)):
- return base.to_python(obj)
- elif isinstance(obj, js_array_type):
- return [_js_object_to_py_object(value) for value in obj.to_list()]
- elif isinstance(obj, jsdate.PyJsDate):
- return obj.to_utc_dt()
- elif isinstance(obj, (base.PyJsNull, base.PyJsUndefined)):
- return None
- elif isinstance(obj, base.PyJsError):
- raise RuntimeError(obj['message'])
- elif isinstance(obj, base.PyJsObject):
- return {
- key: _js_object_to_py_object(value['value'])
- for (key, value) in obj.own.items()
- }
- elif isinstance(obj, base.JsObjectWrapper):
- return _js_object_to_py_object(obj._obj)
+ "Javascript mapping functions require the 'quickjs' package.")
- return obj
+ import json
if expression:
- source = '\n'.join(['function(__row__) {'] + [
- f' {name} = __row__.{name}'
- for name in original_fields if name in expression
- ] + [' return (' + expression + ')'] + ['}'])
- js_func = _CustomJsObjectWrapper(js2py.eval_js(source))
+ source = '\n'.join(
+ ['function fn(json_row) {', ' const __row__ = JSON.parse(json_row);'] +
+ [
+ f' const {name} = __row__.{name};'
+ for name in original_fields if name in expression
+ ] + [' return JSON.stringify(' + expression + ');'] + ['}'])
+ js_func = _QuickJsCallable(source, "fn")
elif callable:
- js_func = _CustomJsObjectWrapper(js2py.eval_js(callable))
+ # Wrap the callable in a named function to use quickjs.Function
+ source = (
+ f"function fn(json_row) {{ "
+ f"const row = JSON.parse(json_row); "
+ f"return JSON.stringify(({callable})(row)); }}")
+ js_func = _QuickJsCallable(source, "fn")
Review Comment:

Manual JSON serialization here is unnecessary and impacts performance. `quickjs` can handle the Python dictionary directly.
```suggestion
source = (
f"function fn(row) {{ "
f"return ({callable})(row); }}")
js_func = _QuickJsCallable(source, "fn")
```
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@beam.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] switch from js2py to quickjs [beam]
Posted by "derrickaw (via GitHub)" <gi...@apache.org>.
derrickaw commented on PR #38130:
URL: https://github.com/apache/beam/pull/38130#issuecomment-4247869357
Run Python_ML PreCommit 3.12
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@beam.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] switch from js2py to quickjs [beam]
Posted by "derrickaw (via GitHub)" <gi...@apache.org>.
derrickaw commented on code in PR #38130:
URL: https://github.com/apache/beam/pull/38130#discussion_r3093202094
##########
sdks/python/apache_beam/yaml/yaml_mapping.py:
##########
@@ -210,78 +225,106 @@ def py_value_to_js_dict(py_value):
def _expand_javascript_mapping_func(
original_fields, expression=None, callable=None, path=None, name=None):
- # Check for installed js2py package
- if js2py is None:
+ # Check for installed quickjs package
+ if quickjs is None:
raise ValueError(
- "Javascript mapping functions are not supported on"
- " Python 3.12 or later.")
-
- # import remaining js2py objects
- from js2py import base
- from js2py.constructors import jsdate
- from js2py.internals import simplex
-
- js_array_type = (
- base.PyJsArray,
- base.PyJsArrayBuffer,
- base.PyJsInt8Array,
- base.PyJsUint8Array,
- base.PyJsUint8ClampedArray,
- base.PyJsInt16Array,
- base.PyJsUint16Array,
- base.PyJsInt32Array,
- base.PyJsUint32Array,
- base.PyJsFloat32Array,
- base.PyJsFloat64Array)
-
- def _js_object_to_py_object(obj):
- if isinstance(obj, (base.PyJsNumber, base.PyJsString, base.PyJsBoolean)):
- return base.to_python(obj)
- elif isinstance(obj, js_array_type):
- return [_js_object_to_py_object(value) for value in obj.to_list()]
- elif isinstance(obj, jsdate.PyJsDate):
- return obj.to_utc_dt()
- elif isinstance(obj, (base.PyJsNull, base.PyJsUndefined)):
- return None
- elif isinstance(obj, base.PyJsError):
- raise RuntimeError(obj['message'])
- elif isinstance(obj, base.PyJsObject):
- return {
- key: _js_object_to_py_object(value['value'])
- for (key, value) in obj.own.items()
- }
- elif isinstance(obj, base.JsObjectWrapper):
- return _js_object_to_py_object(obj._obj)
+ "Javascript mapping functions require the 'quickjs' package.")
- return obj
+ def make_bridge_source(func_name, call_expr):
+ keys_json = json.dumps(list(original_fields))
+ return (
+ f"function {func_name}(serialized_flags, ...values) {{ "
+ f" const keys = JSON.parse('{keys_json}'); "
+ f" const flags = serialized_flags.split(','); "
+ f" const row = {{}}; "
+ f" for (let i = 0; i < keys.length; i++) {{ "
+ f" let val = values[i]; "
+ f" if (flags[i] === '1') val = JSON.parse(val); "
+ f" row[keys[i]] = val; "
+ f" }} "
+ f" const result = {call_expr}; "
+ f" return (typeof result === 'object' && result !== null) "
+ f"? '__json__:' + JSON.stringify(result) : result; "
+ f"}}")
if expression:
- source = '\n'.join(['function(__row__) {'] + [
- f' {name} = __row__.{name}'
- for name in original_fields if name in expression
- ] + [' return (' + expression + ')'] + ['}'])
- js_func = _CustomJsObjectWrapper(js2py.eval_js(source))
+ args = [
+ name for name in original_fields
+ if name.isidentifier() and name in expression
+ ]
+ parses = []
+ for i, arg in enumerate(args):
+ parses.append(f" if (flags[{i}] === '1') {arg} = JSON.parse({arg});")
+
+ source = f"""
+function fn(serialized_flags, {", ".join(args)}) {{
+ const flags = serialized_flags.split(',');
+{chr(10).join(parses)}
+ const result = ({expression});
+ return (typeof result === 'object' && result !== null) ?
+ "__json__:" + JSON.stringify(result) : result;
+}}
+"""
+ js_func = _QuickJsCallable(source, "fn")
+ used_fields = args
elif callable:
- js_func = _CustomJsObjectWrapper(js2py.eval_js(callable))
+ source = make_bridge_source("fn", f"({callable})(row)")
+ js_func = _QuickJsCallable(source, "fn")
+ used_fields = None
else:
if not path.endswith('.js'):
raise ValueError(f'File "{path}" is not a valid .js file.')
udf_code = FileSystems.open(path).read().decode()
- js = js2py.EvalJs()
- js.eval(udf_code)
- js_func = _CustomJsObjectWrapper(getattr(js, name))
+ bridge_source = udf_code + "\n" + make_bridge_source(
+ "bridge_fn", f"{name}(row)")
+ js_func = _QuickJsCallable(bridge_source, "bridge_fn")
+ used_fields = None
def js_wrapper(row):
- row_as_dict = py_value_to_js_dict(row)
- try:
- js_result = js_func(row_as_dict)
- except simplex.JsException as exn:
- raise RuntimeError(
- f"Error evaluating javascript expression: "
- f"{exn.mes['message']}") from exn
- return dicts_to_rows(_js_object_to_py_object(js_result))
+ if expression:
+ vals = [py_value_to_js_dict(getattr(row, name)) for name in used_fields]
+ js_vals = []
+ flags = []
+ for val in vals:
+ if isinstance(val, (list, dict)):
+ js_vals.append(json.dumps(val))
+ flags.append('1')
+ else:
+ js_vals.append(val)
+ flags.append('0')
+
+ flags_str = ",".join(flags)
+ try:
+ js_result = js_func(flags_str, *js_vals)
+ except Exception as exn:
+ raise RuntimeError(
+ f"Error evaluating javascript expression: {exn}") from exn
+ else:
+ row_as_dict = py_value_to_js_dict(row)
+ js_vals = []
+ flags = []
+ for name in original_fields:
+ val = row_as_dict.get(name)
+ if isinstance(val, (list, dict)):
+ js_vals.append(json.dumps(val))
+ flags.append('1')
+ else:
+ js_vals.append(val)
+ flags.append('0')
+
+ flags_str = ",".join(flags)
+ try:
+ js_result = js_func(flags_str, *js_vals)
+ except Exception as exn:
+ raise RuntimeError(
+ f"Error evaluating javascript expression: {exn}") from exn
+
+ if isinstance(js_result, str) and js_result.startswith("__json__:"):
+ js_result = json.loads(js_result[9:])
Review Comment:
removed explicit stringify
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@beam.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] switch from js2py to quickjs [beam]
Posted by "derrickaw (via GitHub)" <gi...@apache.org>.
derrickaw commented on PR #38130:
URL: https://github.com/apache/beam/pull/38130#issuecomment-4260556273
Run PythonLint PreCommit
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@beam.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] switch from js2py to quickjs [beam]
Posted by "derrickaw (via GitHub)" <gi...@apache.org>.
derrickaw commented on PR #38130:
URL: https://github.com/apache/beam/pull/38130#issuecomment-4261103710
Run PythonDocker PreCommit 3.10
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@beam.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] switch from js2py to quickjs [beam]
Posted by "derrickaw (via GitHub)" <gi...@apache.org>.
derrickaw commented on PR #38130:
URL: https://github.com/apache/beam/pull/38130#issuecomment-4237866583
Run Python PreCommit 3.10
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@beam.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] switch from js2py to quickjs [beam]
Posted by "derrickaw (via GitHub)" <gi...@apache.org>.
derrickaw commented on PR #38130:
URL: https://github.com/apache/beam/pull/38130#issuecomment-4254217968
Run PythonDocs PreCommit
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@beam.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] switch from js2py to quickjs [beam]
Posted by "derrickaw (via GitHub)" <gi...@apache.org>.
derrickaw commented on PR #38130:
URL: https://github.com/apache/beam/pull/38130#issuecomment-4254220373
Run Python PreCommit 3.11
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@beam.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] switch from js2py to quickjs [beam]
Posted by "derrickaw (via GitHub)" <gi...@apache.org>.
derrickaw commented on PR #38130:
URL: https://github.com/apache/beam/pull/38130#issuecomment-4248421150
Run PythonDocker PreCommit 3.13
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@beam.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] switch from js2py to quickjs [beam]
Posted by "derrickaw (via GitHub)" <gi...@apache.org>.
derrickaw commented on PR #38130:
URL: https://github.com/apache/beam/pull/38130#issuecomment-4245675382
Run Python PreCommit 3.10
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@beam.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] switch from js2py to quickjs [beam]
Posted by "derrickaw (via GitHub)" <gi...@apache.org>.
derrickaw commented on PR #38130:
URL: https://github.com/apache/beam/pull/38130#issuecomment-4253575860
Run Python PreCommit 3.10
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@beam.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] switch from js2py to quickjs [beam]
Posted by "derrickaw (via GitHub)" <gi...@apache.org>.
derrickaw commented on PR #38130:
URL: https://github.com/apache/beam/pull/38130#issuecomment-4260211201
/gemini review
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@beam.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] switch from js2py to quickjs [beam]
Posted by "derrickaw (via GitHub)" <gi...@apache.org>.
derrickaw commented on PR #38130:
URL: https://github.com/apache/beam/pull/38130#issuecomment-4262378543
Run PythonDocker PreCommit 3.10
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@beam.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] switch from js2py to quickjs [beam]
Posted by "derrickaw (via GitHub)" <gi...@apache.org>.
derrickaw commented on PR #38130:
URL: https://github.com/apache/beam/pull/38130#issuecomment-4253577607
Run Yaml_Xlang_Direct PreCommit
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@beam.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] switch from js2py to quickjs [beam]
Posted by "derrickaw (via GitHub)" <gi...@apache.org>.
derrickaw commented on PR #38130:
URL: https://github.com/apache/beam/pull/38130#issuecomment-4248474806
/gemini review
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@beam.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] switch from js2py to quickjs [beam]
Posted by "derrickaw (via GitHub)" <gi...@apache.org>.
derrickaw commented on code in PR #38130:
URL: https://github.com/apache/beam/pull/38130#discussion_r3086146129
##########
sdks/python/apache_beam/yaml/yaml_mapping.py:
##########
@@ -210,78 +224,49 @@ def py_value_to_js_dict(py_value):
def _expand_javascript_mapping_func(
original_fields, expression=None, callable=None, path=None, name=None):
- # Check for installed js2py package
- if js2py is None:
+ # Check for installed quickjs package
+ if quickjs is None:
raise ValueError(
- "Javascript mapping functions are not supported on"
- " Python 3.12 or later.")
-
- # import remaining js2py objects
- from js2py import base
- from js2py.constructors import jsdate
- from js2py.internals import simplex
-
- js_array_type = (
- base.PyJsArray,
- base.PyJsArrayBuffer,
- base.PyJsInt8Array,
- base.PyJsUint8Array,
- base.PyJsUint8ClampedArray,
- base.PyJsInt16Array,
- base.PyJsUint16Array,
- base.PyJsInt32Array,
- base.PyJsUint32Array,
- base.PyJsFloat32Array,
- base.PyJsFloat64Array)
-
- def _js_object_to_py_object(obj):
- if isinstance(obj, (base.PyJsNumber, base.PyJsString, base.PyJsBoolean)):
- return base.to_python(obj)
- elif isinstance(obj, js_array_type):
- return [_js_object_to_py_object(value) for value in obj.to_list()]
- elif isinstance(obj, jsdate.PyJsDate):
- return obj.to_utc_dt()
- elif isinstance(obj, (base.PyJsNull, base.PyJsUndefined)):
- return None
- elif isinstance(obj, base.PyJsError):
- raise RuntimeError(obj['message'])
- elif isinstance(obj, base.PyJsObject):
- return {
- key: _js_object_to_py_object(value['value'])
- for (key, value) in obj.own.items()
- }
- elif isinstance(obj, base.JsObjectWrapper):
- return _js_object_to_py_object(obj._obj)
+ "Javascript mapping functions require the 'quickjs' package.")
- return obj
+ import json
if expression:
- source = '\n'.join(['function(__row__) {'] + [
- f' {name} = __row__.{name}'
- for name in original_fields if name in expression
- ] + [' return (' + expression + ')'] + ['}'])
- js_func = _CustomJsObjectWrapper(js2py.eval_js(source))
+ source = '\n'.join(
+ ['function fn(json_row) {', ' const __row__ = JSON.parse(json_row);'] +
+ [
+ f' const {name} = __row__.{name};'
+ for name in original_fields if name in expression
+ ] + [' return JSON.stringify(' + expression + ');'] + ['}'])
+ js_func = _QuickJsCallable(source, "fn")
elif callable:
- js_func = _CustomJsObjectWrapper(js2py.eval_js(callable))
+ # Wrap the callable in a named function to use quickjs.Function
+ source = (
+ f"function fn(json_row) {{ "
+ f"const row = JSON.parse(json_row); "
+ f"return JSON.stringify(({callable})(row)); }}")
+ js_func = _QuickJsCallable(source, "fn")
Review Comment:
done
##########
sdks/python/apache_beam/yaml/yaml_mapping.py:
##########
@@ -210,78 +224,49 @@ def py_value_to_js_dict(py_value):
def _expand_javascript_mapping_func(
original_fields, expression=None, callable=None, path=None, name=None):
- # Check for installed js2py package
- if js2py is None:
+ # Check for installed quickjs package
+ if quickjs is None:
raise ValueError(
- "Javascript mapping functions are not supported on"
- " Python 3.12 or later.")
-
- # import remaining js2py objects
- from js2py import base
- from js2py.constructors import jsdate
- from js2py.internals import simplex
-
- js_array_type = (
- base.PyJsArray,
- base.PyJsArrayBuffer,
- base.PyJsInt8Array,
- base.PyJsUint8Array,
- base.PyJsUint8ClampedArray,
- base.PyJsInt16Array,
- base.PyJsUint16Array,
- base.PyJsInt32Array,
- base.PyJsUint32Array,
- base.PyJsFloat32Array,
- base.PyJsFloat64Array)
-
- def _js_object_to_py_object(obj):
- if isinstance(obj, (base.PyJsNumber, base.PyJsString, base.PyJsBoolean)):
- return base.to_python(obj)
- elif isinstance(obj, js_array_type):
- return [_js_object_to_py_object(value) for value in obj.to_list()]
- elif isinstance(obj, jsdate.PyJsDate):
- return obj.to_utc_dt()
- elif isinstance(obj, (base.PyJsNull, base.PyJsUndefined)):
- return None
- elif isinstance(obj, base.PyJsError):
- raise RuntimeError(obj['message'])
- elif isinstance(obj, base.PyJsObject):
- return {
- key: _js_object_to_py_object(value['value'])
- for (key, value) in obj.own.items()
- }
- elif isinstance(obj, base.JsObjectWrapper):
- return _js_object_to_py_object(obj._obj)
+ "Javascript mapping functions require the 'quickjs' package.")
- return obj
+ import json
if expression:
- source = '\n'.join(['function(__row__) {'] + [
- f' {name} = __row__.{name}'
- for name in original_fields if name in expression
- ] + [' return (' + expression + ')'] + ['}'])
- js_func = _CustomJsObjectWrapper(js2py.eval_js(source))
+ source = '\n'.join(
+ ['function fn(json_row) {', ' const __row__ = JSON.parse(json_row);'] +
+ [
+ f' const {name} = __row__.{name};'
+ for name in original_fields if name in expression
+ ] + [' return JSON.stringify(' + expression + ');'] + ['}'])
+ js_func = _QuickJsCallable(source, "fn")
elif callable:
- js_func = _CustomJsObjectWrapper(js2py.eval_js(callable))
+ # Wrap the callable in a named function to use quickjs.Function
+ source = (
+ f"function fn(json_row) {{ "
+ f"const row = JSON.parse(json_row); "
+ f"return JSON.stringify(({callable})(row)); }}")
+ js_func = _QuickJsCallable(source, "fn")
else:
if not path.endswith('.js'):
raise ValueError(f'File "{path}" is not a valid .js file.')
udf_code = FileSystems.open(path).read().decode()
- js = js2py.EvalJs()
- js.eval(udf_code)
- js_func = _CustomJsObjectWrapper(getattr(js, name))
+ bridge_source = (
+ udf_code + f"\nfunction bridge_fn(json_row) {{ "
+ f"return JSON.stringify({name}(JSON.parse(json_row))); }}")
+ js_func = _QuickJsCallable(bridge_source, "bridge_fn")
Review Comment:
done
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@beam.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] switch from js2py to quickjs [beam]
Posted by "derrickaw (via GitHub)" <gi...@apache.org>.
derrickaw commented on PR #38130:
URL: https://github.com/apache/beam/pull/38130#issuecomment-4254216302
Run PythonDocker PreCommit 3.14
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@beam.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] switch from js2py to quickjs [beam]
Posted by "derrickaw (via GitHub)" <gi...@apache.org>.
derrickaw commented on code in PR #38130:
URL: https://github.com/apache/beam/pull/38130#discussion_r3093381269
##########
sdks/python/apache_beam/yaml/yaml_mapping.py:
##########
@@ -210,78 +225,109 @@ def py_value_to_js_dict(py_value):
def _expand_javascript_mapping_func(
original_fields, expression=None, callable=None, path=None, name=None):
- # Check for installed js2py package
- if js2py is None:
+ # Check for installed quickjs package
+ if quickjs is None:
raise ValueError(
- "Javascript mapping functions are not supported on"
- " Python 3.12 or later.")
-
- # import remaining js2py objects
- from js2py import base
- from js2py.constructors import jsdate
- from js2py.internals import simplex
-
- js_array_type = (
- base.PyJsArray,
- base.PyJsArrayBuffer,
- base.PyJsInt8Array,
- base.PyJsUint8Array,
- base.PyJsUint8ClampedArray,
- base.PyJsInt16Array,
- base.PyJsUint16Array,
- base.PyJsInt32Array,
- base.PyJsUint32Array,
- base.PyJsFloat32Array,
- base.PyJsFloat64Array)
-
- def _js_object_to_py_object(obj):
- if isinstance(obj, (base.PyJsNumber, base.PyJsString, base.PyJsBoolean)):
- return base.to_python(obj)
- elif isinstance(obj, js_array_type):
- return [_js_object_to_py_object(value) for value in obj.to_list()]
- elif isinstance(obj, jsdate.PyJsDate):
- return obj.to_utc_dt()
- elif isinstance(obj, (base.PyJsNull, base.PyJsUndefined)):
- return None
- elif isinstance(obj, base.PyJsError):
- raise RuntimeError(obj['message'])
- elif isinstance(obj, base.PyJsObject):
- return {
- key: _js_object_to_py_object(value['value'])
- for (key, value) in obj.own.items()
- }
- elif isinstance(obj, base.JsObjectWrapper):
- return _js_object_to_py_object(obj._obj)
-
- return obj
+ "Javascript mapping functions require the 'quickjs' package.")
+
+ def make_bridge_source(func_name, call_expr):
+ # The bridge function facilitates high-performance data transfer from Python
+ # to QuickJS by reconstructing the row object in JS.
+ # To minimize JSON overhead, primitives are passed directly, while complex
+ # types (lists/dicts) are passed as JSON strings and parsed in JS.
+ # The 'flags' argument indicates which values need parsing.
+ keys_json = json.dumps(list(original_fields))
+ return (
+ f"function {func_name}(serialized_flags, ...values) {{ "
+ f" const keys = {keys_json}; "
+ f" const flags = serialized_flags.split(','); "
+ f" const row = {{}}; "
+ f" for (let i = 0; i < keys.length; i++) {{ "
+ f" let val = values[i]; "
+ f" if (flags[i] === '1') val = JSON.parse(val); "
+ f" row[keys[i]] = val; "
+ f" }} "
+ f" const result = {call_expr}; "
+ f" if (result instanceof Date) "
+ f"return {{__type__: 'date', value: result.toISOString()}}; "
+ f" return result; "
+ f"}}")
if expression:
- source = '\n'.join(['function(__row__) {'] + [
- f' {name} = __row__.{name}'
- for name in original_fields if name in expression
- ] + [' return (' + expression + ')'] + ['}'])
- js_func = _CustomJsObjectWrapper(js2py.eval_js(source))
+ args = [
+ name for name in original_fields
+ if name.isidentifier() and name in expression
+ ]
+ parses = []
+ for i, arg in enumerate(args):
+ parses.append(f" if (flags[{i}] === '1') {arg} = JSON.parse({arg});")
+
+ source = f"""
+function fn(serialized_flags, {", ".join(args)}) {{
Review Comment:
done
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@beam.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] switch from js2py to quickjs [beam]
Posted by "derrickaw (via GitHub)" <gi...@apache.org>.
derrickaw commented on PR #38130:
URL: https://github.com/apache/beam/pull/38130#issuecomment-4261219227
Run Python PreCommit 3.11
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@beam.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] switch from js2py to quickjs [beam]
Posted by "derrickaw (via GitHub)" <gi...@apache.org>.
derrickaw commented on PR #38130:
URL: https://github.com/apache/beam/pull/38130#issuecomment-4262251570
Run Python PreCommit 3.10
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@beam.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] switch from js2py to quickjs [beam]
Posted by "derrickaw (via GitHub)" <gi...@apache.org>.
derrickaw commented on PR #38130:
URL: https://github.com/apache/beam/pull/38130#issuecomment-4245441570
Run Python_Transforms PreCommit 3.12
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@beam.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] switch from js2py to quickjs [beam]
Posted by "derrickaw (via GitHub)" <gi...@apache.org>.
derrickaw commented on PR #38130:
URL: https://github.com/apache/beam/pull/38130#issuecomment-4245846814
Run Python PreCommit 3.10
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@beam.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] switch from js2py to quickjs [beam]
Posted by "derrickaw (via GitHub)" <gi...@apache.org>.
derrickaw commented on PR #38130:
URL: https://github.com/apache/beam/pull/38130#issuecomment-4246298412
Run PythonDocker PreCommit 3.14
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@beam.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] switch from js2py to quickjs [beam]
Posted by "derrickaw (via GitHub)" <gi...@apache.org>.
derrickaw commented on PR #38130:
URL: https://github.com/apache/beam/pull/38130#issuecomment-4261106319
Run Python_ML PreCommit 3.12
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@beam.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] switch from js2py to quickjs [beam]
Posted by "derrickaw (via GitHub)" <gi...@apache.org>.
derrickaw commented on PR #38130:
URL: https://github.com/apache/beam/pull/38130#issuecomment-4261888125
Run PythonDocker PreCommit 3.10
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@beam.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] switch from js2py to quickjs [beam]
Posted by "gemini-code-assist[bot] (via GitHub)" <gi...@apache.org>.
gemini-code-assist[bot] commented on code in PR #38130:
URL: https://github.com/apache/beam/pull/38130#discussion_r3093052974
##########
sdks/python/apache_beam/yaml/yaml_mapping.py:
##########
@@ -210,78 +225,106 @@ def py_value_to_js_dict(py_value):
def _expand_javascript_mapping_func(
original_fields, expression=None, callable=None, path=None, name=None):
- # Check for installed js2py package
- if js2py is None:
+ # Check for installed quickjs package
+ if quickjs is None:
raise ValueError(
- "Javascript mapping functions are not supported on"
- " Python 3.12 or later.")
-
- # import remaining js2py objects
- from js2py import base
- from js2py.constructors import jsdate
- from js2py.internals import simplex
-
- js_array_type = (
- base.PyJsArray,
- base.PyJsArrayBuffer,
- base.PyJsInt8Array,
- base.PyJsUint8Array,
- base.PyJsUint8ClampedArray,
- base.PyJsInt16Array,
- base.PyJsUint16Array,
- base.PyJsInt32Array,
- base.PyJsUint32Array,
- base.PyJsFloat32Array,
- base.PyJsFloat64Array)
-
- def _js_object_to_py_object(obj):
- if isinstance(obj, (base.PyJsNumber, base.PyJsString, base.PyJsBoolean)):
- return base.to_python(obj)
- elif isinstance(obj, js_array_type):
- return [_js_object_to_py_object(value) for value in obj.to_list()]
- elif isinstance(obj, jsdate.PyJsDate):
- return obj.to_utc_dt()
- elif isinstance(obj, (base.PyJsNull, base.PyJsUndefined)):
- return None
- elif isinstance(obj, base.PyJsError):
- raise RuntimeError(obj['message'])
- elif isinstance(obj, base.PyJsObject):
- return {
- key: _js_object_to_py_object(value['value'])
- for (key, value) in obj.own.items()
- }
- elif isinstance(obj, base.JsObjectWrapper):
- return _js_object_to_py_object(obj._obj)
+ "Javascript mapping functions require the 'quickjs' package.")
- return obj
+ def make_bridge_source(func_name, call_expr):
+ keys_json = json.dumps(list(original_fields))
+ return (
+ f"function {func_name}(serialized_flags, ...values) {{ "
+ f" const keys = JSON.parse('{keys_json}'); "
+ f" const flags = serialized_flags.split(','); "
+ f" const row = {{}}; "
+ f" for (let i = 0; i < keys.length; i++) {{ "
+ f" let val = values[i]; "
+ f" if (flags[i] === '1') val = JSON.parse(val); "
+ f" row[keys[i]] = val; "
+ f" }} "
+ f" const result = {call_expr}; "
+ f" return (typeof result === 'object' && result !== null) "
+ f"? '__json__:' + JSON.stringify(result) : result; "
Review Comment:

The use of the `__json__:` prefix to signal serialized objects is prone to collisions. If the JavaScript function returns a string that happens to start with this prefix, it will be incorrectly parsed as JSON in Python, potentially leading to a `JSONDecodeError` or unexpected data transformation. Consider using a more unique sentinel or, since `quickjs` supports returning native Python dictionaries and lists, consider avoiding manual JSON serialization entirely for better performance and reliability.
##########
sdks/python/apache_beam/yaml/yaml_mapping.py:
##########
@@ -178,18 +177,34 @@ def _check_mapping_arguments(
raise ValueError(f'{transform_name} cannot specify "name" without "path"')
-# js2py's JsObjectWrapper object has a self-referencing __dict__ property
-# that cannot be pickled without implementing the __getstate__ and
-# __setstate__ methods.
-class _CustomJsObjectWrapper(JsObjectWrapper):
- def __init__(self, js_obj):
- super().__init__(js_obj.__dict__['_obj'])
+class _QuickJsCallable:
+ def __init__(self, source, name=None):
+ self.source = source
+ self.name = name
+ self._func = None
+
+ def _get_func(self):
+ if self._func is None:
+ if quickjs is None:
+ raise ValueError("quickjs is not installed.")
+ context = quickjs.Context()
+ if self.name:
+ context.eval(self.source)
+ self._func = context.get(self.name)
+ else:
+ self._func = context.eval(self.source)
+ return self._func
+
+ def __call__(self, *args, **kwargs):
+ return self._get_func()(*args, **kwargs)
Review Comment:

The `__call__` method accepts `**kwargs`, but the underlying `quickjs` function call typically only supports positional arguments. If keyword arguments are passed, they may be ignored or cause a `TypeError` depending on the `quickjs` wrapper implementation. It's safer to restrict this to `*args` unless keyword argument support is explicitly intended and verified.
```suggestion
def __call__(self, *args):
return self._get_func()(*args)
```
##########
sdks/python/apache_beam/yaml/yaml_mapping.py:
##########
@@ -210,78 +225,106 @@ def py_value_to_js_dict(py_value):
def _expand_javascript_mapping_func(
original_fields, expression=None, callable=None, path=None, name=None):
- # Check for installed js2py package
- if js2py is None:
+ # Check for installed quickjs package
+ if quickjs is None:
raise ValueError(
- "Javascript mapping functions are not supported on"
- " Python 3.12 or later.")
-
- # import remaining js2py objects
- from js2py import base
- from js2py.constructors import jsdate
- from js2py.internals import simplex
-
- js_array_type = (
- base.PyJsArray,
- base.PyJsArrayBuffer,
- base.PyJsInt8Array,
- base.PyJsUint8Array,
- base.PyJsUint8ClampedArray,
- base.PyJsInt16Array,
- base.PyJsUint16Array,
- base.PyJsInt32Array,
- base.PyJsUint32Array,
- base.PyJsFloat32Array,
- base.PyJsFloat64Array)
-
- def _js_object_to_py_object(obj):
- if isinstance(obj, (base.PyJsNumber, base.PyJsString, base.PyJsBoolean)):
- return base.to_python(obj)
- elif isinstance(obj, js_array_type):
- return [_js_object_to_py_object(value) for value in obj.to_list()]
- elif isinstance(obj, jsdate.PyJsDate):
- return obj.to_utc_dt()
- elif isinstance(obj, (base.PyJsNull, base.PyJsUndefined)):
- return None
- elif isinstance(obj, base.PyJsError):
- raise RuntimeError(obj['message'])
- elif isinstance(obj, base.PyJsObject):
- return {
- key: _js_object_to_py_object(value['value'])
- for (key, value) in obj.own.items()
- }
- elif isinstance(obj, base.JsObjectWrapper):
- return _js_object_to_py_object(obj._obj)
+ "Javascript mapping functions require the 'quickjs' package.")
- return obj
+ def make_bridge_source(func_name, call_expr):
+ keys_json = json.dumps(list(original_fields))
+ return (
+ f"function {func_name}(serialized_flags, ...values) {{ "
+ f" const keys = JSON.parse('{keys_json}'); "
+ f" const flags = serialized_flags.split(','); "
+ f" const row = {{}}; "
+ f" for (let i = 0; i < keys.length; i++) {{ "
+ f" let val = values[i]; "
+ f" if (flags[i] === '1') val = JSON.parse(val); "
+ f" row[keys[i]] = val; "
+ f" }} "
+ f" const result = {call_expr}; "
+ f" return (typeof result === 'object' && result !== null) "
+ f"? '__json__:' + JSON.stringify(result) : result; "
+ f"}}")
if expression:
- source = '\n'.join(['function(__row__) {'] + [
- f' {name} = __row__.{name}'
- for name in original_fields if name in expression
- ] + [' return (' + expression + ')'] + ['}'])
- js_func = _CustomJsObjectWrapper(js2py.eval_js(source))
+ args = [
+ name for name in original_fields
+ if name.isidentifier() and name in expression
+ ]
+ parses = []
+ for i, arg in enumerate(args):
+ parses.append(f" if (flags[{i}] === '1') {arg} = JSON.parse({arg});")
+
+ source = f"""
+function fn(serialized_flags, {", ".join(args)}) {{
+ const flags = serialized_flags.split(',');
+{chr(10).join(parses)}
+ const result = ({expression});
+ return (typeof result === 'object' && result !== null) ?
+ "__json__:" + JSON.stringify(result) : result;
+}}
+"""
+ js_func = _QuickJsCallable(source, "fn")
+ used_fields = args
elif callable:
- js_func = _CustomJsObjectWrapper(js2py.eval_js(callable))
+ source = make_bridge_source("fn", f"({callable})(row)")
+ js_func = _QuickJsCallable(source, "fn")
+ used_fields = None
else:
if not path.endswith('.js'):
raise ValueError(f'File "{path}" is not a valid .js file.')
udf_code = FileSystems.open(path).read().decode()
- js = js2py.EvalJs()
- js.eval(udf_code)
- js_func = _CustomJsObjectWrapper(getattr(js, name))
+ bridge_source = udf_code + "\n" + make_bridge_source(
+ "bridge_fn", f"{name}(row)")
+ js_func = _QuickJsCallable(bridge_source, "bridge_fn")
+ used_fields = None
def js_wrapper(row):
- row_as_dict = py_value_to_js_dict(row)
- try:
- js_result = js_func(row_as_dict)
- except simplex.JsException as exn:
- raise RuntimeError(
- f"Error evaluating javascript expression: "
- f"{exn.mes['message']}") from exn
- return dicts_to_rows(_js_object_to_py_object(js_result))
+ if expression:
+ vals = [py_value_to_js_dict(getattr(row, name)) for name in used_fields]
+ js_vals = []
+ flags = []
+ for val in vals:
+ if isinstance(val, (list, dict)):
+ js_vals.append(json.dumps(val))
+ flags.append('1')
+ else:
+ js_vals.append(val)
+ flags.append('0')
+
+ flags_str = ",".join(flags)
+ try:
+ js_result = js_func(flags_str, *js_vals)
+ except Exception as exn:
+ raise RuntimeError(
+ f"Error evaluating javascript expression: {exn}") from exn
+ else:
+ row_as_dict = py_value_to_js_dict(row)
+ js_vals = []
+ flags = []
+ for name in original_fields:
+ val = row_as_dict.get(name)
+ if isinstance(val, (list, dict)):
+ js_vals.append(json.dumps(val))
+ flags.append('1')
+ else:
+ js_vals.append(val)
+ flags.append('0')
+
+ flags_str = ",".join(flags)
+ try:
+ js_result = js_func(flags_str, *js_vals)
+ except Exception as exn:
+ raise RuntimeError(
+ f"Error evaluating javascript expression: {exn}") from exn
Review Comment:

There is significant code duplication in `js_wrapper` between the `expression` and `non-expression` cases for preparing `js_vals` and `flags`. This logic (iterating over fields, checking for `list`/`dict`, and JSON-encoding them) could be refactored into a helper function to improve maintainability and reduce the risk of logic drift.
##########
sdks/python/apache_beam/yaml/yaml_mapping.py:
##########
@@ -210,78 +225,106 @@ def py_value_to_js_dict(py_value):
def _expand_javascript_mapping_func(
original_fields, expression=None, callable=None, path=None, name=None):
- # Check for installed js2py package
- if js2py is None:
+ # Check for installed quickjs package
+ if quickjs is None:
raise ValueError(
- "Javascript mapping functions are not supported on"
- " Python 3.12 or later.")
-
- # import remaining js2py objects
- from js2py import base
- from js2py.constructors import jsdate
- from js2py.internals import simplex
-
- js_array_type = (
- base.PyJsArray,
- base.PyJsArrayBuffer,
- base.PyJsInt8Array,
- base.PyJsUint8Array,
- base.PyJsUint8ClampedArray,
- base.PyJsInt16Array,
- base.PyJsUint16Array,
- base.PyJsInt32Array,
- base.PyJsUint32Array,
- base.PyJsFloat32Array,
- base.PyJsFloat64Array)
-
- def _js_object_to_py_object(obj):
- if isinstance(obj, (base.PyJsNumber, base.PyJsString, base.PyJsBoolean)):
- return base.to_python(obj)
- elif isinstance(obj, js_array_type):
- return [_js_object_to_py_object(value) for value in obj.to_list()]
- elif isinstance(obj, jsdate.PyJsDate):
- return obj.to_utc_dt()
- elif isinstance(obj, (base.PyJsNull, base.PyJsUndefined)):
- return None
- elif isinstance(obj, base.PyJsError):
- raise RuntimeError(obj['message'])
- elif isinstance(obj, base.PyJsObject):
- return {
- key: _js_object_to_py_object(value['value'])
- for (key, value) in obj.own.items()
- }
- elif isinstance(obj, base.JsObjectWrapper):
- return _js_object_to_py_object(obj._obj)
+ "Javascript mapping functions require the 'quickjs' package.")
- return obj
+ def make_bridge_source(func_name, call_expr):
+ keys_json = json.dumps(list(original_fields))
+ return (
+ f"function {func_name}(serialized_flags, ...values) {{ "
+ f" const keys = JSON.parse('{keys_json}'); "
Review Comment:

Using `JSON.parse` with a single-quoted string literal for `keys_json` is fragile. If any field name in `original_fields` contains a single quote (e.g., `user's_name`), the resulting JavaScript will have a syntax error because the single quote in the field name will prematurely terminate the string literal in `JSON.parse('...')`. Since `keys_json` is already a valid JSON string (and thus a valid JavaScript array literal), you can embed it directly without `JSON.parse`.
```suggestion
f" const keys = {keys_json}; "
```
##########
sdks/python/apache_beam/yaml/yaml_mapping.py:
##########
@@ -210,78 +225,106 @@ def py_value_to_js_dict(py_value):
def _expand_javascript_mapping_func(
original_fields, expression=None, callable=None, path=None, name=None):
- # Check for installed js2py package
- if js2py is None:
+ # Check for installed quickjs package
+ if quickjs is None:
raise ValueError(
- "Javascript mapping functions are not supported on"
- " Python 3.12 or later.")
-
- # import remaining js2py objects
- from js2py import base
- from js2py.constructors import jsdate
- from js2py.internals import simplex
-
- js_array_type = (
- base.PyJsArray,
- base.PyJsArrayBuffer,
- base.PyJsInt8Array,
- base.PyJsUint8Array,
- base.PyJsUint8ClampedArray,
- base.PyJsInt16Array,
- base.PyJsUint16Array,
- base.PyJsInt32Array,
- base.PyJsUint32Array,
- base.PyJsFloat32Array,
- base.PyJsFloat64Array)
-
- def _js_object_to_py_object(obj):
- if isinstance(obj, (base.PyJsNumber, base.PyJsString, base.PyJsBoolean)):
- return base.to_python(obj)
- elif isinstance(obj, js_array_type):
- return [_js_object_to_py_object(value) for value in obj.to_list()]
- elif isinstance(obj, jsdate.PyJsDate):
- return obj.to_utc_dt()
- elif isinstance(obj, (base.PyJsNull, base.PyJsUndefined)):
- return None
- elif isinstance(obj, base.PyJsError):
- raise RuntimeError(obj['message'])
- elif isinstance(obj, base.PyJsObject):
- return {
- key: _js_object_to_py_object(value['value'])
- for (key, value) in obj.own.items()
- }
- elif isinstance(obj, base.JsObjectWrapper):
- return _js_object_to_py_object(obj._obj)
+ "Javascript mapping functions require the 'quickjs' package.")
- return obj
+ def make_bridge_source(func_name, call_expr):
+ keys_json = json.dumps(list(original_fields))
+ return (
+ f"function {func_name}(serialized_flags, ...values) {{ "
+ f" const keys = JSON.parse('{keys_json}'); "
+ f" const flags = serialized_flags.split(','); "
+ f" const row = {{}}; "
+ f" for (let i = 0; i < keys.length; i++) {{ "
+ f" let val = values[i]; "
+ f" if (flags[i] === '1') val = JSON.parse(val); "
+ f" row[keys[i]] = val; "
+ f" }} "
+ f" const result = {call_expr}; "
+ f" return (typeof result === 'object' && result !== null) "
+ f"? '__json__:' + JSON.stringify(result) : result; "
+ f"}}")
if expression:
- source = '\n'.join(['function(__row__) {'] + [
- f' {name} = __row__.{name}'
- for name in original_fields if name in expression
- ] + [' return (' + expression + ')'] + ['}'])
- js_func = _CustomJsObjectWrapper(js2py.eval_js(source))
+ args = [
+ name for name in original_fields
+ if name.isidentifier() and name in expression
+ ]
+ parses = []
+ for i, arg in enumerate(args):
+ parses.append(f" if (flags[{i}] === '1') {arg} = JSON.parse({arg});")
+
+ source = f"""
+function fn(serialized_flags, {", ".join(args)}) {{
+ const flags = serialized_flags.split(',');
+{chr(10).join(parses)}
+ const result = ({expression});
+ return (typeof result === 'object' && result !== null) ?
+ "__json__:" + JSON.stringify(result) : result;
+}}
+"""
+ js_func = _QuickJsCallable(source, "fn")
+ used_fields = args
elif callable:
- js_func = _CustomJsObjectWrapper(js2py.eval_js(callable))
+ source = make_bridge_source("fn", f"({callable})(row)")
+ js_func = _QuickJsCallable(source, "fn")
+ used_fields = None
else:
if not path.endswith('.js'):
raise ValueError(f'File "{path}" is not a valid .js file.')
udf_code = FileSystems.open(path).read().decode()
- js = js2py.EvalJs()
- js.eval(udf_code)
- js_func = _CustomJsObjectWrapper(getattr(js, name))
+ bridge_source = udf_code + "\n" + make_bridge_source(
+ "bridge_fn", f"{name}(row)")
+ js_func = _QuickJsCallable(bridge_source, "bridge_fn")
+ used_fields = None
def js_wrapper(row):
- row_as_dict = py_value_to_js_dict(row)
- try:
- js_result = js_func(row_as_dict)
- except simplex.JsException as exn:
- raise RuntimeError(
- f"Error evaluating javascript expression: "
- f"{exn.mes['message']}") from exn
- return dicts_to_rows(_js_object_to_py_object(js_result))
+ if expression:
+ vals = [py_value_to_js_dict(getattr(row, name)) for name in used_fields]
+ js_vals = []
+ flags = []
+ for val in vals:
+ if isinstance(val, (list, dict)):
+ js_vals.append(json.dumps(val))
+ flags.append('1')
+ else:
+ js_vals.append(val)
+ flags.append('0')
+
+ flags_str = ",".join(flags)
+ try:
+ js_result = js_func(flags_str, *js_vals)
+ except Exception as exn:
+ raise RuntimeError(
+ f"Error evaluating javascript expression: {exn}") from exn
+ else:
+ row_as_dict = py_value_to_js_dict(row)
+ js_vals = []
+ flags = []
+ for name in original_fields:
+ val = row_as_dict.get(name)
+ if isinstance(val, (list, dict)):
+ js_vals.append(json.dumps(val))
+ flags.append('1')
+ else:
+ js_vals.append(val)
+ flags.append('0')
+
+ flags_str = ",".join(flags)
+ try:
+ js_result = js_func(flags_str, *js_vals)
+ except Exception as exn:
+ raise RuntimeError(
+ f"Error evaluating javascript expression: {exn}") from exn
+
+ if isinstance(js_result, str) and js_result.startswith("__json__:"):
+ js_result = json.loads(js_result[9:])
Review Comment:

The switch to JSON-based bridging for complex types results in a loss of automatic type conversion for certain objects, such as JavaScript `Date` objects. In the previous `js2py` implementation, `Date` objects were converted to Python `datetime` objects. With the current `JSON.stringify` approach, they will be converted to ISO strings in Python. If this change in behavior is unintended, you may need to add explicit handling for date types in the bridge.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@beam.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] switch from js2py to quickjs [beam]
Posted by "derrickaw (via GitHub)" <gi...@apache.org>.
derrickaw commented on PR #38130:
URL: https://github.com/apache/beam/pull/38130#issuecomment-4259925687
/gemini review
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@beam.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] switch from js2py to quickjs [beam]
Posted by "derrickaw (via GitHub)" <gi...@apache.org>.
derrickaw commented on PR #38130:
URL: https://github.com/apache/beam/pull/38130#issuecomment-4262253617
Run PythonDocker PreCommit 3.10
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@beam.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] switch from js2py to quickjs [beam]
Posted by "derrickaw (via GitHub)" <gi...@apache.org>.
derrickaw commented on PR #38130:
URL: https://github.com/apache/beam/pull/38130#issuecomment-4268647364
Run Python PreCommit 3.11
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@beam.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] switch from js2py to quickjs [beam]
Posted by "derrickaw (via GitHub)" <gi...@apache.org>.
derrickaw commented on PR #38130:
URL: https://github.com/apache/beam/pull/38130#issuecomment-4254004219
Run Python_Runners PreCommit 3.14
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@beam.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] switch from js2py to quickjs [beam]
Posted by "derrickaw (via GitHub)" <gi...@apache.org>.
derrickaw commented on PR #38130:
URL: https://github.com/apache/beam/pull/38130#issuecomment-4254287335
Run Python PreCommit 3.11
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@beam.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] switch from js2py to quickjs [beam]
Posted by "derrickaw (via GitHub)" <gi...@apache.org>.
derrickaw commented on PR #38130:
URL: https://github.com/apache/beam/pull/38130#issuecomment-4246889297
Run Python PreCommit 3.14
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@beam.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] switch from js2py to quickjs [beam]
Posted by "derrickaw (via GitHub)" <gi...@apache.org>.
derrickaw commented on code in PR #38130:
URL: https://github.com/apache/beam/pull/38130#discussion_r3093228559
##########
sdks/python/apache_beam/yaml/yaml_mapping.py:
##########
@@ -210,78 +225,106 @@ def py_value_to_js_dict(py_value):
def _expand_javascript_mapping_func(
original_fields, expression=None, callable=None, path=None, name=None):
- # Check for installed js2py package
- if js2py is None:
+ # Check for installed quickjs package
+ if quickjs is None:
raise ValueError(
- "Javascript mapping functions are not supported on"
- " Python 3.12 or later.")
-
- # import remaining js2py objects
- from js2py import base
- from js2py.constructors import jsdate
- from js2py.internals import simplex
-
- js_array_type = (
- base.PyJsArray,
- base.PyJsArrayBuffer,
- base.PyJsInt8Array,
- base.PyJsUint8Array,
- base.PyJsUint8ClampedArray,
- base.PyJsInt16Array,
- base.PyJsUint16Array,
- base.PyJsInt32Array,
- base.PyJsUint32Array,
- base.PyJsFloat32Array,
- base.PyJsFloat64Array)
-
- def _js_object_to_py_object(obj):
- if isinstance(obj, (base.PyJsNumber, base.PyJsString, base.PyJsBoolean)):
- return base.to_python(obj)
- elif isinstance(obj, js_array_type):
- return [_js_object_to_py_object(value) for value in obj.to_list()]
- elif isinstance(obj, jsdate.PyJsDate):
- return obj.to_utc_dt()
- elif isinstance(obj, (base.PyJsNull, base.PyJsUndefined)):
- return None
- elif isinstance(obj, base.PyJsError):
- raise RuntimeError(obj['message'])
- elif isinstance(obj, base.PyJsObject):
- return {
- key: _js_object_to_py_object(value['value'])
- for (key, value) in obj.own.items()
- }
- elif isinstance(obj, base.JsObjectWrapper):
- return _js_object_to_py_object(obj._obj)
+ "Javascript mapping functions require the 'quickjs' package.")
- return obj
+ def make_bridge_source(func_name, call_expr):
+ keys_json = json.dumps(list(original_fields))
+ return (
+ f"function {func_name}(serialized_flags, ...values) {{ "
+ f" const keys = JSON.parse('{keys_json}'); "
+ f" const flags = serialized_flags.split(','); "
+ f" const row = {{}}; "
+ f" for (let i = 0; i < keys.length; i++) {{ "
+ f" let val = values[i]; "
+ f" if (flags[i] === '1') val = JSON.parse(val); "
+ f" row[keys[i]] = val; "
+ f" }} "
+ f" const result = {call_expr}; "
+ f" return (typeof result === 'object' && result !== null) "
+ f"? '__json__:' + JSON.stringify(result) : result; "
+ f"}}")
if expression:
- source = '\n'.join(['function(__row__) {'] + [
- f' {name} = __row__.{name}'
- for name in original_fields if name in expression
- ] + [' return (' + expression + ')'] + ['}'])
- js_func = _CustomJsObjectWrapper(js2py.eval_js(source))
+ args = [
+ name for name in original_fields
+ if name.isidentifier() and name in expression
+ ]
+ parses = []
+ for i, arg in enumerate(args):
+ parses.append(f" if (flags[{i}] === '1') {arg} = JSON.parse({arg});")
+
+ source = f"""
+function fn(serialized_flags, {", ".join(args)}) {{
+ const flags = serialized_flags.split(',');
+{chr(10).join(parses)}
+ const result = ({expression});
+ return (typeof result === 'object' && result !== null) ?
+ "__json__:" + JSON.stringify(result) : result;
+}}
+"""
+ js_func = _QuickJsCallable(source, "fn")
+ used_fields = args
elif callable:
- js_func = _CustomJsObjectWrapper(js2py.eval_js(callable))
+ source = make_bridge_source("fn", f"({callable})(row)")
+ js_func = _QuickJsCallable(source, "fn")
+ used_fields = None
else:
if not path.endswith('.js'):
raise ValueError(f'File "{path}" is not a valid .js file.')
udf_code = FileSystems.open(path).read().decode()
- js = js2py.EvalJs()
- js.eval(udf_code)
- js_func = _CustomJsObjectWrapper(getattr(js, name))
+ bridge_source = udf_code + "\n" + make_bridge_source(
+ "bridge_fn", f"{name}(row)")
+ js_func = _QuickJsCallable(bridge_source, "bridge_fn")
+ used_fields = None
def js_wrapper(row):
- row_as_dict = py_value_to_js_dict(row)
- try:
- js_result = js_func(row_as_dict)
- except simplex.JsException as exn:
- raise RuntimeError(
- f"Error evaluating javascript expression: "
- f"{exn.mes['message']}") from exn
- return dicts_to_rows(_js_object_to_py_object(js_result))
+ if expression:
+ vals = [py_value_to_js_dict(getattr(row, name)) for name in used_fields]
+ js_vals = []
+ flags = []
+ for val in vals:
+ if isinstance(val, (list, dict)):
+ js_vals.append(json.dumps(val))
+ flags.append('1')
+ else:
+ js_vals.append(val)
+ flags.append('0')
+
+ flags_str = ",".join(flags)
+ try:
+ js_result = js_func(flags_str, *js_vals)
+ except Exception as exn:
+ raise RuntimeError(
+ f"Error evaluating javascript expression: {exn}") from exn
+ else:
+ row_as_dict = py_value_to_js_dict(row)
+ js_vals = []
+ flags = []
+ for name in original_fields:
+ val = row_as_dict.get(name)
+ if isinstance(val, (list, dict)):
+ js_vals.append(json.dumps(val))
+ flags.append('1')
+ else:
+ js_vals.append(val)
+ flags.append('0')
+
+ flags_str = ",".join(flags)
+ try:
+ js_result = js_func(flags_str, *js_vals)
+ except Exception as exn:
+ raise RuntimeError(
+ f"Error evaluating javascript expression: {exn}") from exn
Review Comment:
good point, done
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@beam.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] switch from js2py to quickjs [beam]
Posted by "derrickaw (via GitHub)" <gi...@apache.org>.
derrickaw commented on PR #38130:
URL: https://github.com/apache/beam/pull/38130#issuecomment-4261882690
Run Python PreCommit 3.10
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@beam.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] switch from js2py to quickjs [beam]
Posted by "derrickaw (via GitHub)" <gi...@apache.org>.
derrickaw closed pull request #38130: switch from js2py to quickjs
URL: https://github.com/apache/beam/pull/38130
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@beam.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] switch from js2py to quickjs [beam]
Posted by "derrickaw (via GitHub)" <gi...@apache.org>.
derrickaw commented on PR #38130:
URL: https://github.com/apache/beam/pull/38130#issuecomment-4247870957
Run PythonDocker PreCommit 3.11
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@beam.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] switch from js2py to quickjs [beam]
Posted by "derrickaw (via GitHub)" <gi...@apache.org>.
derrickaw commented on PR #38130:
URL: https://github.com/apache/beam/pull/38130#issuecomment-4247291007
Run Python PreCommit 3.10
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@beam.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] switch from js2py to quickjs [beam]
Posted by "derrickaw (via GitHub)" <gi...@apache.org>.
derrickaw commented on PR #38130:
URL: https://github.com/apache/beam/pull/38130#issuecomment-4262889184
Run PythonDocker PreCommit 3.10
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@beam.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] switch from js2py to quickjs [beam]
Posted by "gemini-code-assist[bot] (via GitHub)" <gi...@apache.org>.
gemini-code-assist[bot] commented on code in PR #38130:
URL: https://github.com/apache/beam/pull/38130#discussion_r3093329268
##########
sdks/python/apache_beam/yaml/yaml_mapping.py:
##########
@@ -210,78 +225,109 @@ def py_value_to_js_dict(py_value):
def _expand_javascript_mapping_func(
original_fields, expression=None, callable=None, path=None, name=None):
- # Check for installed js2py package
- if js2py is None:
+ # Check for installed quickjs package
+ if quickjs is None:
raise ValueError(
- "Javascript mapping functions are not supported on"
- " Python 3.12 or later.")
-
- # import remaining js2py objects
- from js2py import base
- from js2py.constructors import jsdate
- from js2py.internals import simplex
-
- js_array_type = (
- base.PyJsArray,
- base.PyJsArrayBuffer,
- base.PyJsInt8Array,
- base.PyJsUint8Array,
- base.PyJsUint8ClampedArray,
- base.PyJsInt16Array,
- base.PyJsUint16Array,
- base.PyJsInt32Array,
- base.PyJsUint32Array,
- base.PyJsFloat32Array,
- base.PyJsFloat64Array)
-
- def _js_object_to_py_object(obj):
- if isinstance(obj, (base.PyJsNumber, base.PyJsString, base.PyJsBoolean)):
- return base.to_python(obj)
- elif isinstance(obj, js_array_type):
- return [_js_object_to_py_object(value) for value in obj.to_list()]
- elif isinstance(obj, jsdate.PyJsDate):
- return obj.to_utc_dt()
- elif isinstance(obj, (base.PyJsNull, base.PyJsUndefined)):
- return None
- elif isinstance(obj, base.PyJsError):
- raise RuntimeError(obj['message'])
- elif isinstance(obj, base.PyJsObject):
- return {
- key: _js_object_to_py_object(value['value'])
- for (key, value) in obj.own.items()
- }
- elif isinstance(obj, base.JsObjectWrapper):
- return _js_object_to_py_object(obj._obj)
-
- return obj
+ "Javascript mapping functions require the 'quickjs' package.")
+
+ def make_bridge_source(func_name, call_expr):
+ # The bridge function facilitates high-performance data transfer from Python
+ # to QuickJS by reconstructing the row object in JS.
+ # To minimize JSON overhead, primitives are passed directly, while complex
+ # types (lists/dicts) are passed as JSON strings and parsed in JS.
+ # The 'flags' argument indicates which values need parsing.
+ keys_json = json.dumps(list(original_fields))
+ return (
+ f"function {func_name}(serialized_flags, ...values) {{ "
+ f" const keys = {keys_json}; "
+ f" const flags = serialized_flags.split(','); "
+ f" const row = {{}}; "
+ f" for (let i = 0; i < keys.length; i++) {{ "
+ f" let val = values[i]; "
+ f" if (flags[i] === '1') val = JSON.parse(val); "
+ f" row[keys[i]] = val; "
+ f" }} "
+ f" const result = {call_expr}; "
+ f" if (result instanceof Date) "
+ f"return {{__type__: 'date', value: result.toISOString()}}; "
+ f" return result; "
+ f"}}")
if expression:
- source = '\n'.join(['function(__row__) {'] + [
- f' {name} = __row__.{name}'
- for name in original_fields if name in expression
- ] + [' return (' + expression + ')'] + ['}'])
- js_func = _CustomJsObjectWrapper(js2py.eval_js(source))
+ args = [
+ name for name in original_fields
+ if name.isidentifier() and name in expression
+ ]
+ parses = []
+ for i, arg in enumerate(args):
+ parses.append(f" if (flags[{i}] === '1') {arg} = JSON.parse({arg});")
+
+ source = f"""
+function fn(serialized_flags, {", ".join(args)}) {{
+ const flags = serialized_flags.split(',');
+{chr(10).join(parses)}
+ const result = ({expression});
+ if (result instanceof Date) return {{__type__: 'date', value: result.toISOString()}};
+ return result;
+}}
+"""
+ js_func = _QuickJsCallable(source, "fn")
+ used_fields = args
elif callable:
- js_func = _CustomJsObjectWrapper(js2py.eval_js(callable))
+ source = make_bridge_source("fn", f"({callable})(row)")
+ js_func = _QuickJsCallable(source, "fn")
+ used_fields = None
else:
if not path.endswith('.js'):
raise ValueError(f'File "{path}" is not a valid .js file.')
udf_code = FileSystems.open(path).read().decode()
- js = js2py.EvalJs()
- js.eval(udf_code)
- js_func = _CustomJsObjectWrapper(getattr(js, name))
+ bridge_source = udf_code + "\n" + make_bridge_source(
+ "bridge_fn", f"{name}(row)")
+ js_func = _QuickJsCallable(bridge_source, "bridge_fn")
+ used_fields = None
+
+ def _prepare_args(vals):
+ js_vals = []
+ flags = []
+ for val in vals:
+ if isinstance(val, (list, dict)):
+ js_vals.append(json.dumps(val))
+ flags.append('1')
+ else:
+ js_vals.append(val)
+ flags.append('0')
+ return ",".join(flags), js_vals
def js_wrapper(row):
- row_as_dict = py_value_to_js_dict(row)
+ # Prepare arguments for the JS function. We optimize performance by
+ # passing primitives directly and only serializing complex types (lists,
+ # dicts) to JSON strings. A string of flags ('0' or '1') is passed to
+ # inform the JS bridge which arguments need to be JSON.parsed.
+ if expression:
+ vals = [py_value_to_js_dict(getattr(row, name)) for name in used_fields]
+ else:
+ row_as_dict = py_value_to_js_dict(row)
+ vals = [row_as_dict.get(name) for name in original_fields]
+
+ flags_str, js_vals = _prepare_args(vals)
+
try:
- js_result = js_func(row_as_dict)
- except simplex.JsException as exn:
+ js_result = js_func(flags_str, *js_vals)
+ except Exception as exn:
raise RuntimeError(
- f"Error evaluating javascript expression: "
- f"{exn.mes['message']}") from exn
- return dicts_to_rows(_js_object_to_py_object(js_result))
+ f"Error evaluating javascript expression: {exn}") from exn
+
+ if isinstance(js_result, quickjs.Object):
+ obj = json.loads(js_result.json())
+ if isinstance(obj, dict) and obj.get('__type__') == 'date':
+ import datetime
+ js_result = datetime.datetime.fromisoformat(obj['value'])
Review Comment:

Remove the inline import of `datetime`. This function is called for every row, and while Python caches imports, the repeated lookup is unnecessary. Use the top-level import instead.
```suggestion
js_result = datetime.datetime.fromisoformat(obj['value'])
```
##########
sdks/python/apache_beam/yaml/yaml_mapping.py:
##########
@@ -210,78 +225,109 @@ def py_value_to_js_dict(py_value):
def _expand_javascript_mapping_func(
original_fields, expression=None, callable=None, path=None, name=None):
- # Check for installed js2py package
- if js2py is None:
+ # Check for installed quickjs package
+ if quickjs is None:
raise ValueError(
- "Javascript mapping functions are not supported on"
- " Python 3.12 or later.")
-
- # import remaining js2py objects
- from js2py import base
- from js2py.constructors import jsdate
- from js2py.internals import simplex
-
- js_array_type = (
- base.PyJsArray,
- base.PyJsArrayBuffer,
- base.PyJsInt8Array,
- base.PyJsUint8Array,
- base.PyJsUint8ClampedArray,
- base.PyJsInt16Array,
- base.PyJsUint16Array,
- base.PyJsInt32Array,
- base.PyJsUint32Array,
- base.PyJsFloat32Array,
- base.PyJsFloat64Array)
-
- def _js_object_to_py_object(obj):
- if isinstance(obj, (base.PyJsNumber, base.PyJsString, base.PyJsBoolean)):
- return base.to_python(obj)
- elif isinstance(obj, js_array_type):
- return [_js_object_to_py_object(value) for value in obj.to_list()]
- elif isinstance(obj, jsdate.PyJsDate):
- return obj.to_utc_dt()
- elif isinstance(obj, (base.PyJsNull, base.PyJsUndefined)):
- return None
- elif isinstance(obj, base.PyJsError):
- raise RuntimeError(obj['message'])
- elif isinstance(obj, base.PyJsObject):
- return {
- key: _js_object_to_py_object(value['value'])
- for (key, value) in obj.own.items()
- }
- elif isinstance(obj, base.JsObjectWrapper):
- return _js_object_to_py_object(obj._obj)
-
- return obj
+ "Javascript mapping functions require the 'quickjs' package.")
+
+ def make_bridge_source(func_name, call_expr):
+ # The bridge function facilitates high-performance data transfer from Python
+ # to QuickJS by reconstructing the row object in JS.
+ # To minimize JSON overhead, primitives are passed directly, while complex
+ # types (lists/dicts) are passed as JSON strings and parsed in JS.
+ # The 'flags' argument indicates which values need parsing.
+ keys_json = json.dumps(list(original_fields))
+ return (
+ f"function {func_name}(serialized_flags, ...values) {{ "
+ f" const keys = {keys_json}; "
+ f" const flags = serialized_flags.split(','); "
+ f" const row = {{}}; "
+ f" for (let i = 0; i < keys.length; i++) {{ "
+ f" let val = values[i]; "
+ f" if (flags[i] === '1') val = JSON.parse(val); "
+ f" row[keys[i]] = val; "
+ f" }} "
+ f" const result = {call_expr}; "
+ f" if (result instanceof Date) "
+ f"return {{__type__: 'date', value: result.toISOString()}}; "
+ f" return result; "
+ f"}}")
if expression:
- source = '\n'.join(['function(__row__) {'] + [
- f' {name} = __row__.{name}'
- for name in original_fields if name in expression
- ] + [' return (' + expression + ')'] + ['}'])
- js_func = _CustomJsObjectWrapper(js2py.eval_js(source))
+ args = [
+ name for name in original_fields
+ if name.isidentifier() and name in expression
+ ]
+ parses = []
+ for i, arg in enumerate(args):
+ parses.append(f" if (flags[{i}] === '1') {arg} = JSON.parse({arg});")
+
+ source = f"""
+function fn(serialized_flags, {", ".join(args)}) {{
Review Comment:

When `args` is empty, this generates a trailing comma in the function parameters (e.g., `function fn(serialized_flags, )`). While QuickJS supports this ES2017 feature, it's cleaner and more compatible to avoid it.
```suggestion
function fn(serialized_flags{', ' + ', '.join(args) if args else ''}) {{
```
##########
sdks/python/apache_beam/yaml/yaml_mapping.py:
##########
@@ -178,18 +177,34 @@ def _check_mapping_arguments(
raise ValueError(f'{transform_name} cannot specify "name" without "path"')
-# js2py's JsObjectWrapper object has a self-referencing __dict__ property
-# that cannot be pickled without implementing the __getstate__ and
-# __setstate__ methods.
-class _CustomJsObjectWrapper(JsObjectWrapper):
- def __init__(self, js_obj):
- super().__init__(js_obj.__dict__['_obj'])
+class _QuickJsCallable:
+ def __init__(self, source, name=None):
+ self.source = source
+ self.name = name
+ self._func = None
+
+ def _get_func(self):
+ if self._func is None:
+ if quickjs is None:
+ raise ValueError("quickjs is not installed.")
+ context = quickjs.Context()
+ if self.name:
+ context.eval(self.source)
+ self._func = context.get(self.name)
+ else:
+ self._func = context.eval(self.source)
+ return self._func
Review Comment:

The `_get_func` method lacks thread safety. In multi-threaded environments like the `DirectRunner`, multiple threads might attempt to initialize `self._func` or use the `quickjs.Context` concurrently, which can lead to crashes or undefined behavior as QuickJS contexts are not thread-safe. Consider using a lock or thread-local storage for the context.
##########
sdks/python/apache_beam/yaml/yaml_mapping.py:
##########
@@ -17,6 +17,7 @@
"""This module defines the basic MapToFields operation."""
import itertools
+import json
Review Comment:

Add `import datetime` at the top level to avoid the overhead of importing it inside the per-row wrapper function.
```suggestion
import datetime
import json
```
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@beam.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] switch from js2py to quickjs [beam]
Posted by "derrickaw (via GitHub)" <gi...@apache.org>.
derrickaw commented on PR #38130:
URL: https://github.com/apache/beam/pull/38130#issuecomment-4237866957
Run Python PreCommit 3.11
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@beam.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] switch from js2py to quickjs [beam]
Posted by "derrickaw (via GitHub)" <gi...@apache.org>.
derrickaw commented on PR #38130:
URL: https://github.com/apache/beam/pull/38130#issuecomment-4238853720
Run Python_Examples PreCommit 3.14
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@beam.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] switch from js2py to quickjs [beam]
Posted by "derrickaw (via GitHub)" <gi...@apache.org>.
derrickaw commented on code in PR #38130:
URL: https://github.com/apache/beam/pull/38130#discussion_r3093362944
##########
sdks/python/apache_beam/yaml/yaml_mapping.py:
##########
@@ -178,18 +177,34 @@ def _check_mapping_arguments(
raise ValueError(f'{transform_name} cannot specify "name" without "path"')
-# js2py's JsObjectWrapper object has a self-referencing __dict__ property
-# that cannot be pickled without implementing the __getstate__ and
-# __setstate__ methods.
-class _CustomJsObjectWrapper(JsObjectWrapper):
- def __init__(self, js_obj):
- super().__init__(js_obj.__dict__['_obj'])
+class _QuickJsCallable:
+ def __init__(self, source, name=None):
+ self.source = source
+ self.name = name
+ self._func = None
+
+ def _get_func(self):
+ if self._func is None:
+ if quickjs is None:
+ raise ValueError("quickjs is not installed.")
+ context = quickjs.Context()
+ if self.name:
+ context.eval(self.source)
+ self._func = context.get(self.name)
+ else:
+ self._func = context.eval(self.source)
+ return self._func
Review Comment:
done
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@beam.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] switch from js2py to quickjs [beam]
Posted by "derrickaw (via GitHub)" <gi...@apache.org>.
derrickaw commented on PR #38130:
URL: https://github.com/apache/beam/pull/38130#issuecomment-4270229718
not the right move
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@beam.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] switch from js2py to quickjs [beam]
Posted by "derrickaw (via GitHub)" <gi...@apache.org>.
derrickaw commented on code in PR #38130:
URL: https://github.com/apache/beam/pull/38130#discussion_r3093202094
##########
sdks/python/apache_beam/yaml/yaml_mapping.py:
##########
@@ -210,78 +225,106 @@ def py_value_to_js_dict(py_value):
def _expand_javascript_mapping_func(
original_fields, expression=None, callable=None, path=None, name=None):
- # Check for installed js2py package
- if js2py is None:
+ # Check for installed quickjs package
+ if quickjs is None:
raise ValueError(
- "Javascript mapping functions are not supported on"
- " Python 3.12 or later.")
-
- # import remaining js2py objects
- from js2py import base
- from js2py.constructors import jsdate
- from js2py.internals import simplex
-
- js_array_type = (
- base.PyJsArray,
- base.PyJsArrayBuffer,
- base.PyJsInt8Array,
- base.PyJsUint8Array,
- base.PyJsUint8ClampedArray,
- base.PyJsInt16Array,
- base.PyJsUint16Array,
- base.PyJsInt32Array,
- base.PyJsUint32Array,
- base.PyJsFloat32Array,
- base.PyJsFloat64Array)
-
- def _js_object_to_py_object(obj):
- if isinstance(obj, (base.PyJsNumber, base.PyJsString, base.PyJsBoolean)):
- return base.to_python(obj)
- elif isinstance(obj, js_array_type):
- return [_js_object_to_py_object(value) for value in obj.to_list()]
- elif isinstance(obj, jsdate.PyJsDate):
- return obj.to_utc_dt()
- elif isinstance(obj, (base.PyJsNull, base.PyJsUndefined)):
- return None
- elif isinstance(obj, base.PyJsError):
- raise RuntimeError(obj['message'])
- elif isinstance(obj, base.PyJsObject):
- return {
- key: _js_object_to_py_object(value['value'])
- for (key, value) in obj.own.items()
- }
- elif isinstance(obj, base.JsObjectWrapper):
- return _js_object_to_py_object(obj._obj)
+ "Javascript mapping functions require the 'quickjs' package.")
- return obj
+ def make_bridge_source(func_name, call_expr):
+ keys_json = json.dumps(list(original_fields))
+ return (
+ f"function {func_name}(serialized_flags, ...values) {{ "
+ f" const keys = JSON.parse('{keys_json}'); "
+ f" const flags = serialized_flags.split(','); "
+ f" const row = {{}}; "
+ f" for (let i = 0; i < keys.length; i++) {{ "
+ f" let val = values[i]; "
+ f" if (flags[i] === '1') val = JSON.parse(val); "
+ f" row[keys[i]] = val; "
+ f" }} "
+ f" const result = {call_expr}; "
+ f" return (typeof result === 'object' && result !== null) "
+ f"? '__json__:' + JSON.stringify(result) : result; "
+ f"}}")
if expression:
- source = '\n'.join(['function(__row__) {'] + [
- f' {name} = __row__.{name}'
- for name in original_fields if name in expression
- ] + [' return (' + expression + ')'] + ['}'])
- js_func = _CustomJsObjectWrapper(js2py.eval_js(source))
+ args = [
+ name for name in original_fields
+ if name.isidentifier() and name in expression
+ ]
+ parses = []
+ for i, arg in enumerate(args):
+ parses.append(f" if (flags[{i}] === '1') {arg} = JSON.parse({arg});")
+
+ source = f"""
+function fn(serialized_flags, {", ".join(args)}) {{
+ const flags = serialized_flags.split(',');
+{chr(10).join(parses)}
+ const result = ({expression});
+ return (typeof result === 'object' && result !== null) ?
+ "__json__:" + JSON.stringify(result) : result;
+}}
+"""
+ js_func = _QuickJsCallable(source, "fn")
+ used_fields = args
elif callable:
- js_func = _CustomJsObjectWrapper(js2py.eval_js(callable))
+ source = make_bridge_source("fn", f"({callable})(row)")
+ js_func = _QuickJsCallable(source, "fn")
+ used_fields = None
else:
if not path.endswith('.js'):
raise ValueError(f'File "{path}" is not a valid .js file.')
udf_code = FileSystems.open(path).read().decode()
- js = js2py.EvalJs()
- js.eval(udf_code)
- js_func = _CustomJsObjectWrapper(getattr(js, name))
+ bridge_source = udf_code + "\n" + make_bridge_source(
+ "bridge_fn", f"{name}(row)")
+ js_func = _QuickJsCallable(bridge_source, "bridge_fn")
+ used_fields = None
def js_wrapper(row):
- row_as_dict = py_value_to_js_dict(row)
- try:
- js_result = js_func(row_as_dict)
- except simplex.JsException as exn:
- raise RuntimeError(
- f"Error evaluating javascript expression: "
- f"{exn.mes['message']}") from exn
- return dicts_to_rows(_js_object_to_py_object(js_result))
+ if expression:
+ vals = [py_value_to_js_dict(getattr(row, name)) for name in used_fields]
+ js_vals = []
+ flags = []
+ for val in vals:
+ if isinstance(val, (list, dict)):
+ js_vals.append(json.dumps(val))
+ flags.append('1')
+ else:
+ js_vals.append(val)
+ flags.append('0')
+
+ flags_str = ",".join(flags)
+ try:
+ js_result = js_func(flags_str, *js_vals)
+ except Exception as exn:
+ raise RuntimeError(
+ f"Error evaluating javascript expression: {exn}") from exn
+ else:
+ row_as_dict = py_value_to_js_dict(row)
+ js_vals = []
+ flags = []
+ for name in original_fields:
+ val = row_as_dict.get(name)
+ if isinstance(val, (list, dict)):
+ js_vals.append(json.dumps(val))
+ flags.append('1')
+ else:
+ js_vals.append(val)
+ flags.append('0')
+
+ flags_str = ",".join(flags)
+ try:
+ js_result = js_func(flags_str, *js_vals)
+ except Exception as exn:
+ raise RuntimeError(
+ f"Error evaluating javascript expression: {exn}") from exn
+
+ if isinstance(js_result, str) and js_result.startswith("__json__:"):
+ js_result = json.loads(js_result[9:])
Review Comment:
updated
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@beam.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] switch from js2py to quickjs [beam]
Posted by "derrickaw (via GitHub)" <gi...@apache.org>.
derrickaw commented on PR #38130:
URL: https://github.com/apache/beam/pull/38130#issuecomment-4245256437
Run Python_ML PreCommit 3.13
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@beam.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] switch from js2py to quickjs [beam]
Posted by "derrickaw (via GitHub)" <gi...@apache.org>.
derrickaw commented on PR #38130:
URL: https://github.com/apache/beam/pull/38130#issuecomment-4246475226
Run Python PreCommit 3.11
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@beam.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] switch from js2py to quickjs [beam]
Posted by "derrickaw (via GitHub)" <gi...@apache.org>.
derrickaw commented on PR #38130:
URL: https://github.com/apache/beam/pull/38130#issuecomment-4246608699
Run Python_ML PreCommit 3.11
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@beam.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] switch from js2py to quickjs [beam]
Posted by "derrickaw (via GitHub)" <gi...@apache.org>.
derrickaw commented on PR #38130:
URL: https://github.com/apache/beam/pull/38130#issuecomment-4248419995
Run PythonDocker PreCommit 3.12
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@beam.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] switch from js2py to quickjs [beam]
Posted by "derrickaw (via GitHub)" <gi...@apache.org>.
derrickaw commented on PR #38130:
URL: https://github.com/apache/beam/pull/38130#issuecomment-4253899603
Run Python PreCommit 3.10
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@beam.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] switch from js2py to quickjs [beam]
Posted by "derrickaw (via GitHub)" <gi...@apache.org>.
derrickaw commented on PR #38130:
URL: https://github.com/apache/beam/pull/38130#issuecomment-4253998239
Run Python PreCommit 3.11
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@beam.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] switch from js2py to quickjs [beam]
Posted by "derrickaw (via GitHub)" <gi...@apache.org>.
derrickaw commented on PR #38130:
URL: https://github.com/apache/beam/pull/38130#issuecomment-4254220839
Run Python PreCommit 3.12
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@beam.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] switch from js2py to quickjs [beam]
Posted by "derrickaw (via GitHub)" <gi...@apache.org>.
derrickaw commented on PR #38130:
URL: https://github.com/apache/beam/pull/38130#issuecomment-4254326186
Run Python_ML PreCommit 3.10
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@beam.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org