Repository navigation
feat(v3): add interface-projected service bindings - #5949
mortenolsrud wants to merge 5 commits into
Conversation
|
Important Draft PR not reviewedDraft PRs are not automatically reviewed by default.
To automatically review draft PRs, update your CodeRabbit configuration: reviews:
auto_review:
drafts: trueThanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
189c6c5 to
6fd5d1f
Compare
|
This is great and something that I experimented with early on in the service development. Things to consider before merging:
|
There was a problem hiding this comment.
Pull request overview
Adds interface-projected service registration to Wails v3 so apps can register a concrete Go service while exposing only an explicitly declared (named) interface to the frontend, with both runtime dispatch and generated bindings constrained to the projection.
Changes:
- Introduces
NewServiceAs/NewServiceAsWithOptionsand threads abindingProjectionthrough service registration and runtime binding discovery. - Updates the generator analyser + collector so generated JS/TS bindings and obfuscation metadata include only projected methods.
- Adds runtime/generator tests and updates the Services documentation to describe projection usage and constraints.
Reviewed changes
Copilot reviewed 14 out of 14 changed files in this pull request and generated 2 comments.
Show a summary per file
| File | Description |
|---|---|
| v3/pkg/application/services.go | Adds projected-service constructors and stores the projection type on Service. |
| v3/pkg/application/services_test.go | Adds coverage for options + lifecycle retention with projected services. |
| v3/pkg/application/bindings.go | Filters bound methods by an optional named-interface projection and validates projections at runtime. |
| v3/pkg/application/bindings_test.go | Adds runtime tests ensuring projected methods are callable and non-projected methods are unreachable by name/ID. |
| v3/internal/generator/testdata/service_projection/service.go | New generator fixture registering a projected service. |
| v3/internal/generator/testdata/service_projection/backend/service.go | New backend fixture service with both projected and backend-only methods. |
| v3/internal/generator/service.go | Passes projection information into service collection/generation. |
| v3/internal/generator/service_projection_test.go | New tests asserting generated bindings/metadata include only projected methods. |
| v3/internal/generator/generate.go | Schedules generation for discovered ServiceBinding values (type + optional projection). |
| v3/internal/generator/collect/service.go | Filters collected service methods to those declared by the projection interface (when present). |
| v3/internal/generator/collect/package.go | Stores service collection state including the associated projection. |
| v3/internal/generator/analyse.go | Adds projected-service discovery (NewServiceAs*) and yields ServiceBinding (type + projection). |
| v3/internal/generator/analyse_test.go | Updates analyser expectations to account for ServiceBinding results. |
| docs/src/content/docs/features/bindings/services.mdx | Documents interface projections, constraints, and security rationale vs //wails:ignore. |
💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.
Add NewServiceAs registration variants that expose only a named interface while retaining the concrete service for backend and lifecycle use. Keep runtime dispatch, generated bindings, and obfuscation metadata on the same fail-closed method set. Refs wailsapp#5948
6fd5d1f to
5094174
Compare
|
Thanks — addressed in 5094174 after rebasing onto current
Validation passed for the full application and generator package suites, application race tests, focused generator race tests, scoped vet, legacy GTK3 application tests, a Windows amd64 cross-build, formatting, and diff checks. |
|
@leaanthony Ok, based on feedback from @fbbdev on issue #5948 I went down a rabbit hole, and after discussing with a colleague, and having Claude inspect suitability for our suggestions in the code-base, I have some discoveries to share. Sorry for the wall, I had to have Claude summarize the thing. It got a bit long, but now it at least is shorter ;) Summary of the service-binding discussionfbbdev’s feedback identified that the original issue and PR combine two related but distinct concerns:
What the existing Wails model can already doThe current
Go promotes only the methods declared by the embedded interface. Although its dynamic value is an Existing registration remains: This already provides a runtime-enforced allowlist because the backend methods are absent from the wrapper’s Go method set. The explicit forwards in the current library can therefore be removed. fbbdev also showed how the library can mark the generated façade as internal and provide JS/TS re-exports so frontend users see: while the underlying generated and runtime identity remains: For This means the original claim that Wails necessarily requires maintaining forwarding methods was too strong. It requires a second concrete type, but that type can be a very small embedded-interface façade. Library-controlled registration providerWe then considered taking that pattern further by letting a service tell Wails which service should actually be registered:
The library would implement:
Applications would then use ordinary registration: Wails would receive the returned
This requires no additional fields in It also makes the safe library surface the default. A consumer using the normal registration API cannot accidentally expose the complete Generator requirementsProvider detection cannot be runtime-only. The generator must make the same substitution. For: it must recognise that The provider contract should therefore be fail-closed:
Returning Relationship to |
| NewServiceAs | Registration provider | |
|---|---|---|
| Exposure policy owned by | Application | Library |
| Registration style | Explicit projection constructor | Ordinary NewService |
| Concrete façade required | No | Yes, but no forwarding |
| Bound identity | Original concrete service | Library-returned service |
| Lifecycle target | Original concrete service | Library-returned service |
| Best suited for | App-specific narrowing | Library-enforced safe defaults |
fbbdev’s feedback weakens the forwarding-boilerplate motivation for NewServiceAs, but does not invalidate it. NewServiceAs still offers capabilities that the façade/provider approach does not:
- An application can narrow a service it owns or consumes.
- No second concrete service type is needed.
- Concrete service identity, module name, lifecycle, routing, and IDs are retained.
- The projection can be defined locally by the application.
- It is useful when the desired frontend surface is application-specific rather than library-defined.
The PR description should therefore stop presenting explicit forwarding façades as unavoidable. Its motivation would be stronger if framed around application-controlled least privilege, preserving concrete identity, and enforcing one interface consistently across runtime and generation.
It should also acknowledge the embedded-interface façade as an existing library-controlled alternative and explain the tradeoff instead of presenting NewServiceAs as its universal replacement.
If both paths are considered useful
The provider should be a separate proposal and implementation PR because it changes the behavior of the existing NewService API, whereas NewServiceAs adds a new opt-in constructor. They share motivation and generator infrastructure, but have different semantics and review risks.
A formal proposal could discuss both as part of one service-exposure model, while keeping their implementations separate.
Their interaction must nevertheless be defined. In particular:
application.NewServiceAs[SomeAPI](authSvc)must not accidentally bypass a library-controlled provider.
The safest coexistence rule would be:
- Resolve the library provider first.
- Treat the returned service as the maximum surface the library permits.
- Apply
SomeAPIas a further narrowing of that effective service. - Reject the registration if the returned service does not implement the requested projection.
Conceptually:
original service
→ library-provided safe service
→ optional application projectionThis lets an application expose less than the library permits, but not more.
Supporting that rule would eventually require changes around NewServiceAs:
- Share provider resolution with
NewService. - Apply
bindingProjectionto the effective returned service. - Validate that the effective service implements the projection.
- Make the generator follow the same provider-then-projection sequence.
- Key conflicts and generated identity to the effective concrete service.
- Add tests proving that a projection can narrow a provider façade but cannot recover backend-only methods.
For non-provider services, NewServiceAs would behave exactly as the current PR specifies.
Overall conclusion
Three valid levels now emerge:
- Embedded-interface façade: works with Wails today and removes forwarding boilerplate.
- Registration provider: makes a library-owned façade the safe default behind ordinary
NewService. NewServiceAs: gives applications explicit control over registration-time narrowing while preserving concrete identity.
For wails-pkceflow, the embedded façade plus provider contract appears especially natural because the library should define its safe frontend API. NewServiceAs remains independently useful for application-owned services and application-specific projections.
|
Hi all, I am going to comment first on the idea of registration providers. After that, I'll discuss a couple implementation details for the projection feature, since there is interest in it. Registration providersI like the idea a lot. It's clean, simple, and it doesn't require major changes to the binding generator. On the DX side, it could create some issues with people heavily bent on moving all logic to the frontend. Personally, as a library author, I skew towards a "consenting adults" model à la Python. But in this case Wails is simply making a design choice available to library authors, and there is no reason to expect a negative impact on Wails itself. Having the Off the top of my head, the only required changes should be:
By the way, I suggest renaming the provider method I agree that it makes sense to implement this as a separate PR, and because it's such a minimal change my suggestion is to open and merge it before the present one, which is a bit more complex. A difficulty and tentative solutionOne minor inconvenience is that the binding generator won't be able to automatically alias the registration provider to the actual registered service. Not just because it would require complex control flow analysis (that we chose to avoid long ago due to the excessive maintenance burden) but also because in some situations it might not be well-defined, for example if the registration provider returns different services depending on runtime configuration. A possible solution might be to give up the func (_ *Provider) ServiceInstance() *Twhere T must be a named, non-interface type (validated by the binding generator). Then we could generate bindings for Apart from a loss of flexibility, the big issue with this approach is on the runtime side: since we can't use type assertions, we'd have to look up the method using reflection, and I'm not 100% sure it would stay compatible with garble. Another potential solution would be to offer an API along the lines of type RegistrationProvider ...
func init() {
application.ServiceAlias[RegistrationProvider, RealService]()
}Then validate at runtime that alias registrations are unique, and moreover check in The binding generator could then discover instantiations of Though at this point I really feel we would be sliding into WEP territory as it would be nice to get some community feedback on API design.
|
The projection featureAs a separate comment, since the other one grew into a wall 😅. The implementation looks good to me overall. I'd rework the public API slightly; I will present the approach first and then discuss rationale. func NewServiceAs[P any, T any](instance *T) Service {
// ...
}
func NewServiceAsWithOptions[P any, T any](instance *T, options ServiceOptions) Service {
service := NewServiceAs[P](instance)
service.options = options
return service
}
func NewService[T any](instance *T) Service {
return NewServiceAs[T](instance)
}
func NewServiceWithOptions[T any](instance *T, options ServiceOptions) Service {
return NewServiceAsWithOptions[T](instance, options)
}Invariants enforced at binding generation time (build time):
Invariants enforced at binding registration time (run time):
The semantics of letting RationaleThe main reason for this change is to preserve the current discovery logic based on iterating over generic instantiations returned from Avoiding AST scans is a decision we made long ago with @leaanthony because:
A couple years ago I had actually implemented a full-blown static analyser capable of discovering service types through arbitrarily long chains of non-concrete expressions, but we scrapped it in favour of the approach based on concrete generics because we determined it would be too fragile in face of planned/proposed future changes to the language. What is lost:
What stays the same:
What is gained:
|
Merge wailsapp#6137 into wailsapp#5949 without rewriting original commits; add all nine documentation translations.
|
Ported the service-binding projection documentation onto #6137 ( Validation passed: pinned M-Press Translation compatibility remains with the upstream task: 7,679 findings versus 7,678 at migration Required |
|
Whitespace-only follow-up to the #6137 docs port: removed the single extra blank line introduced before the following heading in each of the nine translated projection sections (9 files, 9 blank-line deletions). English, all prose/code, and audit exemptions are unchanged; the German proper-name stale-hash finding remains untouched. No additional migration merge. Validation: strict M-Press build Audit delta with the pinned CLI: 7,679 → 7,679, byte-identical finding lists. Its existing earlier per-page structure mismatches mask the later blank-line mismatch; all nine inserted section boundaries now match English. Full compatibility remains with the upstream translation task; no exemptions added. |
Description
Adds interface-projected service registration for Wails v3. Applications can keep a full concrete Go service while exposing only an explicitly declared interface to the frontend:
NewServiceAsWithOptions[FrontendAuth](authSvc, options)provides the equivalent options-bearing registration.Why this is needed
NewServicecurrently registers every exported method on the concrete service. That is convenient for application-only services, but it forces libraries with mixed frontend and backend responsibilities to add forwarding facade structs solely to define a trust boundary.The motivating case is
wails-pkceflow. Its frontend should callLogin,Logout, status, and claims methods, while Go needsClient,Pause, andResume. Today the wrapper maintains a separateFrontendService, forwards six methods plus lifecycle hooks, and asks applications to registerauthSvc.Frontend(). The facade has no domain behavior; it exists only because Wails cannot filter registration.Generator directives such as
//wails:ignoreare not sufficient for this use case. They remove methods from generated JavaScript or TypeScript, but the low-level runtime can still dispatch a registered method by name or ID. A security-sensitive boundary has to be enforced by runtime registration as well as code generation.How it works
NewServiceAs[API](instance)records the named interface projection while retaining the original concrete instance.API.ServiceName,ServiceStartup,ServiceShutdown, HTTP routing, and backend access continue to use the concrete instance and are independent of the frontend projection.NewServiceandNewServiceWithOptionsbehavior is unchanged.Why an interface instead of a string allowlist
Tradeoffs and limitations
NewServiceAsorNewServiceAsWithOptionscall. Passing an interface-typed variable, or hiding the call behind a generic wrapper whose argument remains a type parameter, produces a warning because the concrete generated module cannot be identified. A non-generic helper with a concrete service parameter works.Servicevalue stores one additionalreflect.Type; ordinary unprojected services leave it nil.Type of change
How Has This Been Tested?
Repository coverage
go test -count=1 ./...fromv3(full suite, including the existing generator matrix)go test -race -count=1 ./pkg/applicationgo test -race -count=1 ./internal/generator -run 'TestFindProjectedService|TestGenerateProjectedService'go vet ./internal/generatorgo vet -unsafeptr=false ./pkg/applicationgo test -count=1 -tags gtk3 ./pkg/application./pkg/applicationand./internal/generatorgit diff --checkandgofmt -lon all changed Go filesNew tests cover:
wails-pkceflowapplication validationI copied and adapted the real
examples/wails-desktopmodule to register*AuthServicedirectly through the six-method interface shown above, with this branch replacing Wails locally.Verified:
Client,Pause,Resume, and the oldFrontendfacade register by neither name nor stable ID;AuthServiceexports match runtime IDs exactly;wails_obfuscatedtests pass;go vet ./...passes in the adapted application;Environment notes
go vet ./...still reports existing diagnostics in intentional generator fixtures and existing Linuxunsafe.Pointercode. Scoped vet for both changed packages passes as listed above.Checklist
Closes #5948