SurrealQL: Bug In JavaScript Embedding In Browser

by Pedro Alvarez 50 views

Hey guys! Let's dive into a fascinating bug report concerning JavaScript embedding within SurrealQL, specifically when used in a browser environment. It seems like there's a snag preventing this feature from working as expected, even when the scripting capability is explicitly enabled. Let's break down the issue, the steps to reproduce it, and what the expected behavior should be. We'll also explore the potential implications and how this might affect developers using SurrealDB in their web applications.

Describe the Bug

The core of the issue lies in the fact that JavaScript embedding in SurrealQL isn't functioning correctly within a browser environment. Even when you diligently set capabilities.scripting = true during the initialization of surrealdbWasmEngines, the embedded JavaScript functions stubbornly refuse to cooperate. It's like telling your car to start, but it just sits there, engine silent and unresponsive.

Digging deeper, the TypeScript definitions in node_modules/@surrealdb/wasm/dist/surreal/types.d.ts seem to suggest that scripting should indeed be supported. The definitions clearly outline the option to enable scripting within the ConnectionOptions:

type ConnectionOptions = {
 strict?: boolean;
 query_timeout?: number;
 transaction_timeout?: number;
 capabilities?: boolean | {
 scripting?: boolean;
 guest_access?: boolean;
 live_query_notifications?: boolean;
 functions?: boolean | string[] | CapabilitiesAllowDenyList;
 network_targets?: boolean | string[] | CapabilitiesAllowDenyList;
 experimental?: boolean | string[] | CapabilitiesAllowDenyList;
 };
};
export declare function surrealdbWasmEngines(opts?: ConnectionOptions): Engines;

This tantalizing bit of code hints at the possibility of seamless JavaScript integration. However, the reality is that any attempt to execute embedded JavaScript functions within a query results in a resounding failure. This is particularly frustrating because the promise of blending the power of JavaScript with the data manipulation capabilities of SurrealQL is quite appealing. Imagine the possibilities – dynamic data transformations, complex calculations, and custom logic all within your database queries!

The ability to embed JavaScript within SurrealQL queries opens up a world of opportunities for developers. It allows for intricate data manipulations, the integration of external JavaScript libraries, and the creation of highly customized database logic. This feature could significantly streamline development workflows and empower developers to build more sophisticated applications. However, with the current bug preventing its proper functioning in the browser environment, these benefits remain just out of reach.

The failure of JavaScript embedding not only limits the functionality of SurrealDB in the browser but also introduces a level of inconsistency between the documented capabilities and the actual behavior. Developers who rely on the documentation to guide their implementation efforts may find themselves facing unexpected roadblocks and wasted time. Addressing this bug is crucial to ensure that SurrealDB lives up to its promise and provides a reliable and consistent experience across different environments.

Steps to Reproduce

To illustrate this issue, let's walk through the steps to reproduce it. Imagine you're a detective trying to reconstruct a crime scene – in this case, the crime is the malfunctioning JavaScript embedding. Here's the code you'd use:

import { Surreal } from "surrealdb";
import { surrealdbWasmEngines } from '@surrealdb/wasm';

async function runSurrealDBDemo() {
 try {
 const db = new Surreal({
 engines: surrealdbWasmEngines({
 capabilities: { scripting: true },
 }),
 });

 await db.connect('indxdb://bugdemo');
 await db.use({ namespace: 'test', database: 'test' });

 const result = await db.query(`
 CREATE person SET
 name = 'Jane Doe',
 scores = function() {
 return [1, 2, 3].map(v => v * 10);
 };
 `);

 console.log('Query Result: ' + JSON.stringify(result, null, 2));
 } catch (error) {
 console.log('Error: ' + (error as Error).message);
 console.error('Detailed error:', error);
 }
}

runSurrealDBDemo();

This code snippet attempts to create a person record in SurrealDB, setting the scores field using an embedded JavaScript function. The function simply multiplies the elements of an array by 10. Seems straightforward enough, right? But when you run this code in a browser environment, you'll be greeted with the following error:

Problem with embedded script function. Embedded functions are not enabled.

This error message is the smoking gun, confirming our suspicion that JavaScript embedding isn't working as intended. It's like trying to use a key to unlock a door, only to find that the lock is jammed. No matter how hard you try, the door remains firmly shut. This error consistently appears even though we've explicitly enabled scripting in the connection options. This is the core of the bug, the discrepancy between what we expect and what we actually get.

The significance of this reproduction lies in its simplicity. The code is concise and clearly demonstrates the problem. This makes it easier for developers to understand the issue and for the SurrealDB team to identify the root cause and implement a fix. By providing a clear and reproducible example, the bug report effectively communicates the problem and facilitates a faster resolution.

Expected Behaviour

The expected behavior, and what any reasonable developer would assume, is that setting capabilities.scripting = true should indeed enable embedded JavaScript functions in SurrealQL when using surrealdbWasmEngines within a browser environment. It's like ordering a pizza with extra cheese and expecting, well, extra cheese! The code clearly states the intention to enable scripting, and the system should honor that request. This expectation is not just based on wishful thinking; it's grounded in the documentation and the logical flow of how the system should operate.

Imagine the smooth, seamless experience of writing SurrealQL queries that incorporate JavaScript logic. You could perform complex data transformations, interact with external APIs, and create highly customized database operations, all within the familiar confines of your queries. This would significantly enhance the flexibility and power of SurrealDB, making it an even more attractive option for developers building web applications.

However, the current bug disrupts this envisioned workflow. Instead of the smooth integration of JavaScript, developers are met with frustrating error messages and the need to find workarounds. This not only slows down development but also limits the potential of SurrealDB in the browser environment. The inability to use JavaScript embedding forces developers to rely on alternative methods, which may be less efficient or less elegant.

The correct behavior is crucial for the overall usability and adoption of SurrealDB. Developers expect the tools they use to function as documented and to provide a consistent experience across different platforms. When features don't work as expected, it erodes trust and can lead to frustration. By fixing this bug and ensuring that JavaScript embedding works correctly, the SurrealDB team can reaffirm their commitment to providing a reliable and powerful database solution.

SurrealDB Version

For the sake of clarity and to aid in debugging, the SurrealDB version in use is @surrealdb/wasm 1.4.1. This information is crucial for the development team as they investigate the bug. Knowing the specific version helps them narrow down the potential causes and identify any version-specific issues. It's like telling a mechanic the make and model of your car – it helps them diagnose the problem much more effectively.

The version number acts as a fingerprint, uniquely identifying the specific build of the software that is exhibiting the bug. This allows the developers to examine the codebase corresponding to that version and trace the execution flow to pinpoint the source of the error. It also helps them determine whether the bug is a regression – meaning it was introduced in a specific version – or if it has been present for a longer period.

Providing the SurrealDB version is a standard practice in bug reporting and is essential for efficient troubleshooting. It eliminates ambiguity and ensures that the developers are working with the correct context. This simple piece of information can save significant time and effort in the debugging process, ultimately leading to a faster resolution of the issue.

Contact Details

For further communication and clarification, the reporter can be reached on Discord at discord:parleyhammon. Providing contact details is a crucial step in the bug reporting process. It opens a channel for direct communication between the reporter and the development team, allowing for a more interactive and efficient resolution.

Imagine the development team has a question about the bug report – perhaps they need more information about the specific environment in which the bug was encountered, or they want to clarify a particular step in the reproduction process. Having contact details readily available allows them to reach out to the reporter and get the answers they need quickly. This collaborative approach can significantly speed up the debugging process.

Discord, with its real-time messaging capabilities, is an ideal platform for this type of communication. It allows for instant back-and-forth interaction, making it easier to discuss the bug in detail and share relevant information. This direct line of communication can be invaluable in complex bug investigations.

Is There an Existing Issue for This?

Before submitting this report, a diligent search was conducted to ensure that this issue isn't already documented. The reporter has confirmed: [x] I have searched the existing issues. This is a crucial step in bug reporting, as it prevents duplicate reports and helps to keep the issue tracker organized. It's like checking to see if someone else has already called dibs on the last slice of pizza – you don't want to step on anyone's toes!

Searching existing issues not only avoids duplication but also allows the reporter to learn from previous discussions and solutions. If a similar issue has been reported before, there might be a workaround or a temporary fix that can be applied. Even if the issue hasn't been fully resolved, the existing discussion can provide valuable insights and context.

By confirming that a search has been conducted, the reporter demonstrates a commitment to contributing constructively to the project. It shows that they have taken the time to investigate the issue thoroughly before submitting a new report. This helps to build trust and fosters a collaborative environment within the community.

Code of Conduct

Finally, the reporter affirms their commitment to upholding the project's standards by stating: [x] I agree to follow this project's Code of Conduct. This is a vital declaration, signifying a pledge to engage in respectful and constructive communication within the project community. It's like signing a social contract, agreeing to abide by the rules of the game and treat fellow players with courtesy and consideration.

A Code of Conduct outlines the expected behavior of contributors and users within a project. It sets the tone for a positive and inclusive environment, where everyone feels welcome and respected. By agreeing to the Code of Conduct, the reporter signals their willingness to participate in a manner that aligns with these principles.

This commitment is particularly important in bug reporting, where discussions can sometimes become heated or frustrating. By adhering to the Code of Conduct, the reporter helps to ensure that the conversation remains focused on the issue at hand and that all participants feel comfortable sharing their perspectives. This ultimately leads to a more productive and collaborative resolution process.

In conclusion, this bug report highlights a significant issue with JavaScript embedding in SurrealQL within a browser environment. The steps to reproduce the bug are clearly outlined, the expected behavior is articulated, and the reporter has provided all the necessary information for the development team to investigate and resolve the issue. Addressing this bug will be crucial for unlocking the full potential of SurrealDB and ensuring a smooth and consistent experience for developers. Let's hope this gets fixed soon, guys!