Skip to content

[v3] Built-in service standardisation and enhancement #4050

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed

Conversation

fbbdev
Copy link
Collaborator

@fbbdev fbbdev commented Feb 7, 2025

Description

⚠️ DO NOT MERGE ⚠️

Requires #4045
TODO: update docs
NOTE: this is a synthetic set of commits on top of v3-alpha to facilitate reviews and discussion. The new implementation is built on top of #4045. Clone fbbdev/wails:v3-alpha-feature/service-api for local testing.

This PR drafts some changes meant to standardise and enhance the API of built-in services (fileserver, kvstore, log, sqlite), partly along the lines of the discussions that took place on Discord here and here.

The new API is mostly compatible with the existing one, but has some minor breaking changes.

All services now adhere to the following conventions:

  • The service type is called Service for consistent JS imports (fileserver and sqlite used this convention already).
  • New() function initialises the service with a sane default configuration (breaking).
  • NewWithConfig(config *Config) allows consumers to provide a custom initial configuration.
  • Service.Configure(config *Config) allows late configuration and dynamic reconfiguration.
  • Service.Configure is never exposed to the frontend, because it could allow arbitrary accesses to the filesystem.
  • All methods must be callable concurrently without issue.
  • The API must make sense from the Go side as well as from the JS side.

fileserver

  • Mostly unchanged
  • The default configuration (nil config => no root specified) responds to all requests with 503 Service Unavailable.

kvstore

  • Default configuration (nil config => no filename specified) provides an in-memory store. Load and Save methods have no effect.
  • New method Service.Load() replaces the current content of the store with those of the associated file.
  • Method Service.Save() writes the current content of the store to the associated file.
  • New method Service.Clear() empties the store.

On-disk stores are always loaded at startup and saved at shutdown. A clarifying comment has been added to the AutoSave option.

What if one wishes to load from disk, but then keep in-memory only or write to another file? There you go:

// Associate with <file1>
store := kvstore.NewWithConfig(&kvstore.Config{Filename: "<file1>"})

// Load from <file1>
err := store.Load() // handle error

// Reattach to <file2>, this time with autosave
store.Configure(&kvstore.Config{
	Filename: "<file2>",
	AutoSave: true,
})

// Save to <file2>
err := store.Save() // handle error

// Detach from <file2>, becomes in-memory store, loads and saves have no effect
store.Configure(nil)

Notice how Service.Configure changes the configuration but does not alter the state otherwise, i.e. all data is kept, no automatic loads or saves are performed.

log

  • Default configuration (nil) writes to application.DefaultLogger(slog.LevelInfo)
  • New level type log.Level publishes Debug/Info/Warning/Error constants to JS
  • New method Service.Log(ctx context.Context, level Level, message string, args ...any) logs with dynamic level. When called from JS, it receives the binding call context that links to the source window. Custom handlers may access this value.
  • New methods Service.DebugContext, Service.InfoContext etc., matching the slog API, accept a context; they are exported to js as Debug, Info etc and receive the binding call context.

The logger implements the slog.Leveler interface to provide dynamic level configuration to custom handlers. See doc comment of the Service.Level method for an example.

sqlite

  • Default configuration (nil) creates an in-memory database.
  • The database is opened automatically at startup and closed at shutdown.
  • Service.Configure method changes the configuration but does not close or reopen the DB.
  • Service.Open() opens (if closed) or reopens the DB, applying the latest configuration.
  • Service.Close() closes the DB if open; has no effect if closed.
  • Service.Select(...) renamed to Service.Query(...) for consistency with sql.DB.
  • New methods Service.ExecContext(...) and Service.QueryContext(...) accept a context for cancellation support. These are exported to JS as Exec and Query, hence cancellation is always supported from JS.
  • New method Service.Prepare(query string) (cancelable version Service.PrepareContext) creates prepared statements.

Normally statements must be closed manually, but they are closed automatically upon calling Service.Close(). Unlike regular sql.Stmts, their Close method is idempotent.

Advanced binding generator features are used to bring prepared statements to the JS side!

import { Service as sqlite } from "<bindings>/github.com/wailsapp/wails/v3/pkg/services/sqlite";

let stmt = await sqlite.Prepare("SELECT * FROM table WHERE id=?");
let result1 = await stmt.Query("id1");
let result2 = await stmt.Query("id2");
let promise = stmt.Query("id3");
promise.cancel(); // We're having second thoughts.
await promise;
await stmt.Close();

Type of change

  • Bug fix (non-breaking change which fixes an issue)
  • New feature (non-breaking change which adds functionality)
  • Breaking change (fix or feature that would cause existing functionality to not work as expected)
  • This change requires a documentation update

How Has This Been Tested?

Ran the services example and verified everything's working fine.

  • Windows
  • macOS
  • Linux

Test Configuration

 Wails (v3.0.0-dev)  Wails Doctor

# System

┌────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
| Name          | MacOS                                                                                                          |
| Version       | 12.6.6                                                                                                         |
| ID            | 21G646                                                                                                         |
| Branding      | Monterey                                                                                                       |
| Platform      | darwin                                                                                                         |
| Architecture  | amd64                                                                                                          |
| Apple Silicon | unknown                                                                                                        |
| CPU           | Intel(R) Core(TM) i7-9750H CPU @ 2.60GHz                                                                       |
| CPU           | Intel(R) Core(TM) i7-9750H CPU @ 2.60GHz                                                                       |
| GPU           |  cores, Metal Family: Supported, Metal GPUFamily macOS 2                                                       |
|       Metal Family: Supported, Metal GPUFamily macOS 2                                                                         |
| Memory        | 32 GB                                                                                                          |
└────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘

# Build Environment

┌─────────────────────────────────────────────────────────┐
| Wails CLI    | v3.0.0-dev                               |
| Go Version   | go1.23.5                                 |
| Revision     | b88d57cbd960c985bd57bab3e13ead10d1618da9 |
| Modified     | false                                    |
| -buildmode   | exe                                      |
| -compiler    | gc                                       |
| CGO_CFLAGS   |                                          |
| CGO_CPPFLAGS |                                          |
| CGO_CXXFLAGS |                                          |
| CGO_ENABLED  | 1                                        |
| CGO_LDFLAGS  |                                          |
| GOAMD64      | v1                                       |
| GOARCH       | amd64                                    |
| GOOS         | darwin                                   |
| vcs          | git                                      |
| vcs.modified | false                                    |
| vcs.revision | b88d57cbd960c985bd57bab3e13ead10d1618da9 |
| vcs.time     | 2025-02-06T14:05:25Z                     |
└─────────────────────────────────────────────────────────┘

# Dependencies

┌───────────────────────────┐
| Xcode cli tools | 2395    |
| npm             | 10.8.2  |
| *NSIS           | v3.10   |
└─ * - Optional Dependency ─┘

# Checking for issues

 SUCCESS  No issues found

# Diagnosis

 SUCCESS  Your system is ready for Wails development!

Checklist:

  • I have updated website/src/pages/changelog.mdx with details of this PR
  • My code follows the general coding style of this project
  • I have performed a self-review of my own code
  • I have commented my code, particularly in hard-to-understand areas
  • I have made corresponding changes to the documentation
  • My changes generate no new warnings
  • I have added tests that prove my fix is effective or that my feature works
  • New and existing unit tests pass locally with my changes

Copy link
Contributor

coderabbitai bot commented Feb 7, 2025

Important

Review skipped

Draft detected.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@fbbdev
Copy link
Collaborator Author

fbbdev commented Feb 13, 2025

Closing in favour of #4067

@fbbdev fbbdev closed this Feb 13, 2025
@fbbdev fbbdev deleted the v3-alpha-feature/service-api-draft branch February 13, 2025 02:15
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant