Skip to content

refactor dix dep render#30

Merged
kooksee merged 1 commit intov2from
feat/render1
Dec 30, 2025
Merged

refactor dix dep render#30
kooksee merged 1 commit intov2from
feat/render1

Conversation

@kooksee
Copy link
Collaborator

@kooksee kooksee commented Dec 30, 2025

Summary by CodeRabbit

  • New Features

    • Added HTTP visualization module for interactive dependency graphs with REST API endpoints
    • Introduced context utilities for managing DI containers
    • Added graph generation with configurable options (max depth, package filtering, grouping)
    • Enhanced logging via structured logging integration
    • Added new generic injection helpers and version accessor
  • Documentation

    • Expanded README with installation, quick start, and comprehensive examples
    • Added HTTP visualization module documentation
    • Added design documentation and architectural overview
  • Improvements

    • Better error handling with improved panic recovery and stack traces
    • Refined dependency inspection APIs
    • Enhanced visual dependency analysis tools

✏️ Tip: You can customize this high-level summary in your review settings.

@coderabbitai
Copy link

coderabbitai bot commented Dec 30, 2025

Important

Review skipped

Auto reviews are disabled on base/target branches other than the default branch.

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.

Note

Other AI code review bot(s) detected

CodeRabbit has detected other AI code review bot(s) in this pull request and will avoid duplicating their findings in the review comments. This may lead to a less comprehensive review.

📝 Walkthrough

Walkthrough

This PR updates dix to v2, introducing a new dixrender package for graph generation, dixhttp package for HTTP-based dependency visualization, and dixcontext for context integration. Refactors internal error handling with slog logging, moves public Graph APIs to dixrender, and updates all example code and documentation to reflect v2 module paths.

Changes

Cohort / File(s) Summary
Version & Build Configuration
.version/VERSION, .gitignore, Makefile, go.mod
Version file added (v2.0.0-beta.7); .env added to gitignore; Makefile test target refactored to dixinternal/... with coverage reporting; go.mod updated to v2 module path, Go 1.24.0, and simplified dependencies.
Public API Restructuring
dix.go
Graph and GraphOptions now reference dixrender instead of dixinternal; new ReleaseVersion(), SetLog(), InjectTT, NewGraphOptions() functions; GenerateGraph wrappers added; embedded VERSION file for version retrieval.
Core DI Infrastructure
dixinternal/dix.go, dixinternal/api.go, dixinternal/provider.go
Reworked provider execution and value resolution with error returns instead of result wrappers; panic-recovery with stack traces; replaced Graph() method with introspection helpers (GetProviders, GetObjects, GetProviderDetails); replaced assertion-based error handling with explicit panics and error returns.
Internal Utilities & Logging
dixinternal/logger.go, dixinternal/util.go, dixinternal/cycle-check.go
New slog-based logger with Tint integration and SetLog() function; GetFnName() utility added; receiver names standardized to "dix"; removed DOT renderer from dixinternal (moved to dixrender).
Removed Rendering (dixinternal)
dixinternal/renderer.go
Entire DOT renderer deleted (providerGraph, providerGraphTypes, objectGraph, DotRenderer type all removed); rendering logic moved to dixrender package.
New: Graph Rendering Package
dixrender/renderer.go, dixrender/graph.go, dixrender/adapter.go
New public DOT renderer API (DotRenderer, Graph, GraphOptions); graph generation functions (GenerateGraph, GenerateProviderGraph, GenerateProviderGraphTypes, GenerateObjectGraph) with filtering and clustering options; adapter pattern (NewDixAdapter) to expose dixinternal providers via reflection-wrapped interfaces.
New: Context Integration
dixcontext/context.go
New package with GetOrNil(), Get(), and Create() functions to attach/retrieve dix.Dix instances from context.Context with error logging and panic on missing values.
New: HTTP Visualization
dixhttp/server.go, dixhttp/example.go, dixhttp/README.md, dixhttp/template.html
New HTTP server exposing REST endpoints (/api/dependencies) and interactive vis-network UI for dependency visualization; includes example usage documentation.
Global DI Access
dixglobal/global.go
Updated imports to v2; public _dix initialization and Graph() function now delegate to dix.GenerateGraph(); new InjectTT and GraphWithOptions() functions added.
Documentation & Design
README.md, docs/design.md
Expanded README with installation, quick start, features, and examples; new design document outlining architecture, workflows, and module breakdown.
Comprehensive Tests
dixinternal/dix_test.go
Large new test suite covering container creation, provider registration, struct/interface/map/list injections, error handling, options, and graph integration.
Example Updates
example/*.go, example/go.mod, example/graph-options/main.go, example/http/main.go
All example imports updated to v2 paths; replaced recovery.Exit() and funk utilities with inline panic handlers; updated to use v2 API (Graph generation, error types); new graph-options and http examples added demonstrating new features.

Sequence Diagram(s)

sequenceDiagram
    participant Client as Browser Client
    participant HTTPServer as dixhttp Server
    participant Handler as HTTP Handler
    participant Dix as Dix Container
    participant Adapter as DixAdapter
    participant Renderer as dixrender

    Client->>HTTPServer: GET /api/dependencies
    HTTPServer->>Handler: HandleDependencies(w, r)
    Handler->>Handler: extractDependencyData()
    Handler->>Dix: GetProviders()
    Dix-->>Handler: map[Type][]ProviderFn
    Handler->>Dix: GetObjects()
    Dix-->>Handler: map[Type]map[Group][]Value
    Handler->>Handler: Build ProviderInfo, ObjectInfo, EdgeInfo
    Handler->>Client: JSON Response (providers, objects, edges)
    
    Client->>HTTPServer: GET /api/graph?type=providers
    HTTPServer->>Handler: Generate graph request
    Handler->>Adapter: NewDixAdapter(dix)
    Adapter-->>Handler: DixAccessor interface
    Handler->>Renderer: GenerateProviderGraph(adapter, opts)
    Renderer->>Adapter: GetProviders()
    Adapter-->>Renderer: Wrapped providers via reflection
    Renderer->>Adapter: GetFnName(), GetInputTypes()
    Renderer-->>Handler: DOT string
    Handler->>Client: Graph visualization (HTML with DOT rendering)
Loading

Estimated code review effort

🎯 5 (Critical) | ⏱️ ~120 minutes

The changes span 50+ files with intricate, multi-pattern transformations: new dixrender and dixhttp packages introduce complex graph generation and HTTP visualization logic; core dixinternal refactoring overhauls error handling, logging, and provider execution; significant public API restructuring (Graph relocation, new introspection methods); heterogeneous changes across documentation, examples, and dependencies; large test suite covering multiple injection patterns and edge cases.

Possibly related PRs

  • Feat/render #25: Adds ProviderTypes output and providerGraphTypes graph generation logic, directly related to this PR's graph-rendering refactor and provider graph visualization restructuring into dixrender.
  • Refactor/cost speed #23: Performs the same large-scale refactor of dix internals—package restructuring (dixinternal/dixglobal), provider/renderer/graph overhauls, and tooling updates—sharing the same architectural transformation at the code level.

Poem

🐰 A hop, skip, and render—
From v1 to v2, we venture!
Graphs dance in HTTP light,
Contexts flow, injections tight.
The dix bounces bold and new!

Pre-merge checks and finishing touches

❌ Failed checks (1 warning, 1 inconclusive)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 51.40% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
Title check ❓ Inconclusive The title 'refactor dix dep render' is vague and uses non-descriptive abbreviations that don't clearly convey the scope of changes. Clarify the title to be more specific, e.g., 'Extract dependency graph rendering into dixrender package' or 'Refactor graph rendering and introduce dixrender package'.
✅ Passed checks (1 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@kooksee kooksee changed the base branch from master to v2 December 30, 2025 12:40
@gemini-code-assist
Copy link

Summary of Changes

Hello @kooksee, I'm Gemini Code Assist1! 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 introduces a significant refactoring and enhancement of the dix dependency injection framework. The primary goal is to improve the framework's internal architecture, provide robust error handling, and offer powerful new visualization tools for understanding complex dependency graphs. These changes aim to make dix more maintainable, debuggable, and user-friendly, especially for larger applications.

Highlights

  • Refactored Package Structure: The core dix package has been updated to dix/v2, and internal components are now organized into dix/v2/dixinternal and a new dix/v2/dixrender package for graph visualization logic.
  • Dependency Graph Visualization: Introduced a new dixrender package for generating Graphviz DOT format dependency graphs and a dixhttp package that provides an HTTP server for interactive, web-based visualization of the DI container's providers and objects.
  • Improved Error Handling and Logging: The internal error handling mechanism has been streamlined, moving away from github.com/pubgo/funk utilities to standard Go errors and panic/recover patterns. Logging now utilizes log/slog for better structured and configurable output.
  • Enhanced Documentation and Examples: The README.md has been significantly expanded with detailed installation instructions, quick start guides, core features, and comprehensive usage examples for various injection patterns. New examples for graph options and HTTP visualization have also been added.
  • New dixcontext Package: A new dixcontext package has been introduced to facilitate storing and retrieving Dix container instances within a context.Context, promoting better context management in applications.
  • Makefile and Versioning Updates: The Makefile now includes a vet target for static analysis and an updated test target with coverage reporting. The framework's version is now embedded directly into the binary using //go:embed.

🧠 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 to enable Memory in your admin console.

Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

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.

Customization

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.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 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.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

Copy link

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request significantly enhances the dependency visualization tool by adding search, filtering, and improved node label formatting. The refactoring of the JavaScript code is a great step towards better maintainability. My review focuses on the new client-side logic, where I've identified a few critical issues in the label formatting functions that could display incorrect information, and I've also suggested some performance improvements for deep cloning objects.

Comment on lines +427 to +438
for (let i = packageParts.length - partsToTry; i < packageParts.length; i++) {
if (i < 0) continue;
const part = packageParts[i];
const candidate = part + '.' + result;

if (candidate.length <= maxLength) {
result = candidate;
} else {
// 如果加上当前包名部分超过限制,添加省略号并返回
return '...' + result;
}
}

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

critical

The loop for prepending package parts to the type name is incorrect. It iterates from the middle of the package path instead of from the end. This results in incorrectly formatted labels, for example a.b.c.MyType could be shortened to c.b.MyType instead of the expected b.c.MyType.

Suggested change
for (let i = packageParts.length - partsToTry; i < packageParts.length; i++) {
if (i < 0) continue;
const part = packageParts[i];
const candidate = part + '.' + result;
if (candidate.length <= maxLength) {
result = candidate;
} else {
// 如果加上当前包名部分超过限制,添加省略号并返回
return '...' + result;
}
}
for (let i = 1; i <= partsToTry; i++) {
const partIndex = packageParts.length - i;
if (partIndex < 0) continue;
const part = packageParts[partIndex];
const candidate = part + '.' + result;
if (candidate.length <= maxLength) {
result = candidate;
} else {
// 如果加上当前包名部分超过限制,添加省略号并返回
return '...' + result;
}
}

Comment on lines +480 to +481
const parts = functionName.split('.');
const packageParts = parts.length > 0 ? parts : [];

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

critical

The logic for splitting the function name into package parts is incorrect. It includes the function name itself in packageParts, and it doesn't handle trailing dots in the functionName which can occur for methods. This leads to incorrect label generation.

Suggested change
const parts = functionName.split('.');
const packageParts = parts.length > 0 ? parts : [];
const parts = functionName.replace(/\.$/, '').split('.');
const packageParts = parts.length > 1 ? parts.slice(0, -1) : [];

Comment on lines +507 to +518
for (let i = packageParts.length - partsToTry; i < packageParts.length; i++) {
if (i < 0) continue;
const part = packageParts[i];
const candidate = part + '.' + result;

if (candidate.length <= maxLength) {
result = candidate;
} else {
// 如果加上当前包名部分超过限制,添加省略号并返回
return '...' + result;
}
}

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

critical

The loop for prepending package parts to the function name is incorrect. It iterates from the middle of the package path instead of from the end, which will result in incorrectly formatted labels.

Suggested change
for (let i = packageParts.length - partsToTry; i < packageParts.length; i++) {
if (i < 0) continue;
const part = packageParts[i];
const candidate = part + '.' + result;
if (candidate.length <= maxLength) {
result = candidate;
} else {
// 如果加上当前包名部分超过限制,添加省略号并返回
return '...' + result;
}
}
for (let i = 1; i <= partsToTry; i++) {
const partIndex = packageParts.length - i;
if (partIndex < 0) continue;
const part = packageParts[partIndex];
const candidate = part + '.' + result;
if (candidate.length <= maxLength) {
result = candidate;
} else {
// 如果加上当前包名部分超过限制,添加省略号并返回
return '...' + result;
}
}

Comment on lines +1358 to +1359
allNodes = JSON.parse(JSON.stringify(nodes));
allEdges = JSON.parse(JSON.stringify(edges));

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

Using JSON.parse(JSON.stringify(...)) for deep cloning can be inefficient for large graphs and has limitations (e.g., it doesn't handle all data types correctly). The modern structuredClone() function is more performant and robust for this task.

Suggested change
allNodes = JSON.parse(JSON.stringify(nodes));
allEdges = JSON.parse(JSON.stringify(edges));
allNodes = structuredClone(nodes);
allEdges = structuredClone(edges);

if (network) {
// 创建节点副本以避免修改原始数据
const nodesToDisplay = filteredNodes.map(node => {
const nodeCopy = JSON.parse(JSON.stringify(node));

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

Using JSON.parse(JSON.stringify(...)) for deep cloning inside a loop can be inefficient, especially for larger graphs. The modern structuredClone() function is more performant and robust for this task.

Suggested change
const nodeCopy = JSON.parse(JSON.stringify(node));
const nodeCopy = structuredClone(node);

@kooksee kooksee force-pushed the feat/render1 branch 2 times, most recently from a62c75d to 1dba8a8 Compare December 30, 2025 13:19
@kooksee kooksee merged commit 0aa0615 into v2 Dec 30, 2025
2 checks passed
kooksee added a commit that referenced this pull request Dec 31, 2025
@kooksee kooksee deleted the feat/render1 branch January 18, 2026 05:11
@coderabbitai coderabbitai bot mentioned this pull request Jan 18, 2026
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

Comments