Skip to content

Conversation

@nixel2007
Copy link
Collaborator

@nixel2007 nixel2007 commented Jun 19, 2025

Fix #1554

Summary by CodeRabbit

  • New Features

    • Introduced a script caching system to speed up repeated loading of OneScript libraries, with automatic cache validation and configurable enablement.
    • Added a package loader module for managing classes, modules, and external components via manifest or directory structure.
    • Added extensive serialization support for script modules, enabling efficient caching.
    • Integrated caching options and controls into configuration settings.
    • Added service registrations for caching and serialization in engine builder extensions.
    • Added a new GitHub Actions workflow for development environment setup.
  • Bug Fixes

    • Improved handling and validation of cache files to prevent loading invalid or outdated cache entries.
    • Enhanced error message formatting and localization for better clarity.
    • Added precise error position reporting in directive handler.
  • Documentation

    • Added detailed guides on script caching and package loader usage.
    • Updated build and workflow documentation for development and testing.
  • Tests

    • Added unit tests for script caching validity checks and caching behavior.
  • Chores

    • Updated project dependencies and build scripts for platform compatibility and new features.
    • Improved .gitignore rules for test artifacts.
    • Simplified build scripts by removing custom tasks and adding platform-specific conditions.

Mr-Rm and others added 17 commits May 29, 2025 12:45
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Jun 19, 2025

Walkthrough

A comprehensive script caching system was introduced for pre-compiling and caching script modules to accelerate repeated loading. This includes new interfaces, services, file-based cache storage, metadata tracking, module serialization, and integration into the library loader. Extensive documentation, configuration options, and tests were also added.

Changes

Files/Paths Change Summary
src/ScriptEngine.HostedScript/LibraryCache/...
src/OneScript.Core/Compilation/...
src/ScriptEngine/Compilation/...
Added interfaces and classes for script cache service (IScriptCacheService, DefaultScriptCacheService, IScriptCacheStorage, FileSystemScriptCache), module serialization (IModuleSerializer, StackRuntimeModuleSerializer, SerializableModule and related classes), and cache metadata tracking.
src/ScriptEngine.HostedScript/LibraryLoader.cs Integrated caching into the library loader: attempts to load modules from cache before compiling, and saves compiled modules to cache. Updated constructors and factory methods to accept cache service.
src/ScriptEngine/Machine/Contexts/AttachedScriptsFactory.cs Commented out previous caching logic; added a helper for file-based source detection (currently unused).
src/ScriptEngine.HostedScript/OneScriptLibraryOptions.cs Added script caching configuration option (ScriptCachingEnabled), with logic for enabling/disabling via config/environment.
src/ScriptEngine.HostedScript/Extensions/EngineBuilderExtensions.cs
src/ScriptEngine/Hosting/EngineBuilderExtensions.cs
Registered caching and serialization services in dependency injection setup.
src/OneScript.Core/Compilation/Binding/SymbolBinding.cs
src/ScriptEngine/Machine/Core.cs
Added MessagePack serialization attributes to support binary serialization of core structs.
src/OneScript.Core/Contexts/BslScriptMethodInfo.cs
src/ScriptEngine/Machine/MachineMethodInfo.cs
Added constructors and helpers to support deserialization of method info from cache.
src/OneScript.Language/Sources/SourceCode.cs Added public property to expose code source origin.
src/OneScript.Core/OneScript.Core.csproj
src/ScriptEngine/ScriptEngine.csproj
Added NuGet dependency on MessagePack for serialization.
.github/workflows/copilot-setup-steps.yml
.github/copilot-instructions.md
Added GitHub Actions workflow for environment setup and a markdown file with build instructions.
oscript_modules/package-loader.os Added a package loader module supporting manifest and convention-based loading, duplicate checks, and logging.
src/Tests/OneScript.HostedScript.Tests/... Added new test project and test verifying cache validity checks.
CACHE_DEMO.md
CACHE_IMPLEMENTATION.md
Added documentation describing the caching system, implementation, usage, and testing.
src/1Script.sln
src/Tests/OneScript.HostedScript.Tests/OneScript.HostedScript.Tests.csproj
Added new test project to the solution.
.gitignore Updated to ignore additional test result files and script cache files.
Build.csproj Added Linux-specific build step conditions and simplified runner property assignment.
tests/**/*.metadata.json Added metadata JSON files for test scripts, storing cache metadata for test sources.
src/ScriptEngine/ScriptingEngine.cs
src/ScriptEngine/OneScriptCoreOptions.cs
Minor whitespace changes only.
src/OneScript.Language/LanguageDef.cs Added dictionary for keywords with canonical names and aliases; modified keyword registration and added methods to retrieve token names and aliases; removed Not from binary operators.
src/OneScript.Language/ScriptException.cs Improved error message formatting by inserting a marker at error column within code line.
src/OneScript.Language/SyntaxAnalysis/DefaultBslParser.cs Simplified error recovery in BuildExpressionUpTo; refined error column adjustment in AddError.
src/OneScript.Language/SyntaxAnalysis/LocalizedErrors.cs Enhanced TokenExpected method to produce localized, specific error messages depending on expected tokens count.
src/OneScript.Language/SyntaxAnalysis/ModuleAnnotationDirectiveHandler.cs Added error position context when reporting disabled directive errors.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant PackageLoader
    participant LibraryLoader
    participant ScriptCacheService
    participant ScriptCacheStorage
    participant Compiler

    User->>PackageLoader: Request to load script/module
    PackageLoader->>LibraryLoader: Add class/module (ДобавитьКласс/ДобавитьМодуль)
    LibraryLoader->>ScriptCacheService: TryLoadFromCache(path)
    alt Cache hit
        ScriptCacheService->>ScriptCacheStorage: Exists & IsValid
        ScriptCacheStorage-->>ScriptCacheService: Cached module
        ScriptCacheService-->>LibraryLoader: Return cached module
    else Cache miss
        ScriptCacheService->>ScriptCacheStorage: Exists or not valid
        ScriptCacheStorage-->>ScriptCacheService: No valid cache
        LibraryLoader->>Compiler: Compile source file
        Compiler-->>LibraryLoader: Compiled module
        LibraryLoader->>ScriptCacheService: SaveToCache(module)
        ScriptCacheService->>ScriptCacheStorage: Store(module)
    end
    LibraryLoader-->>PackageLoader: Module handle
    PackageLoader-->>User: Script loaded
Loading

Assessment against linked issues

Objective Addressed Explanation
Implement pre-compilation and caching for loaded scripts/modules (#1554)
Store and validate cache metadata (modification date, size, runtime version) for scripts (#1554)
Automatically check for cache, validate, and update cache as needed during loading (#1554)
Integrate caching into package loader and library loader workflows (#1554)

Assessment against linked issues: Out-of-scope changes

Code Change Explanation
Addition of .github/workflows/copilot-setup-steps.yml and .github/copilot-instructions.md CI/CD and build documentation setup is unrelated to the caching objectives of #1554.
Update to .gitignore for test result files Ignoring additional test output is not related to script caching or pre-compilation.
Build system changes in Build.csproj for Linux/Windows Build step conditions and runner assignment are not related to caching or pre-compilation of scripts.
Addition of oscript_modules/package-loader.os While related to loading, the package loader module's full implementation is broader than just caching integration.
Minor whitespace changes in src/ScriptEngine/ScriptingEngine.cs, src/ScriptEngine/OneScriptCoreOptions.cs Purely cosmetic changes, not relevant to caching objectives.

Possibly related PRs

Poem

🐇✨
Hop, hop, the scripts now zoom,
With cache in place, there’s so much room!
No more waiting, no more dread,
Pre-compiled magic lies ahead.
Metadata guards each rabbit’s stash,
Loading modules in a flash!
Caching’s here—let’s celebrate, dash!


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
🪧 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.
    • Explain this complex logic.
    • 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 explain this code block.
    • @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 explain its main purpose.
    • @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.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

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.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @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.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

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.

@nixel2007 nixel2007 marked this pull request as ready for review June 19, 2025 14:51
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 5

♻️ Duplicate comments (1)
src/ScriptEngine/ScriptEngine.csproj (1)

49-51: Duplicate: Ensure consistent MessagePack version across projects
This MessagePack reference should match the one added to OneScript.Core.csproj. Consider centralizing the version in a common props file to avoid mismatches.

🧹 Nitpick comments (11)
src/OneScript.Core/OneScript.Core.csproj (1)

9-11: Consistency of MessagePack package version
Added a MessagePack reference. Confirm the version aligns across all csproj files and consider centralizing it in a shared props file (e.g., Directory.Build.props) to prevent duplication and drift.

src/OneScript.Language/Sources/SourceCode.cs (1)

36-36: Add XML documentation for the Origin property
The new public Origin property exposes the private _source. Please add XML <summary> comments to clarify its purpose and any usage considerations.

src/ScriptEngine/Machine/Core.cs (1)

146-152: Review MessagePack serialization keys and version compatibility
Marking Code and Argument with keys 0 and 1 enables binary serialization via MessagePack. Ensure this ordering matches any existing serialized data and consider adopting version-tolerant options (e.g., key-as-name or union attributes) to support future schema changes.

src/ScriptEngine/Machine/MachineMethodInfo.cs (2)

17-21: Translate inline comment and remove redundant base() call
The Russian comment // Внутренний конструктор для десериализации из кэша should be translated to English (e.g., // Internal constructor for deserialization from cache). Also, the explicit : base() invocation is redundant on both constructors and can be omitted.


23-27: Clarify default constructor behavior and add XML docs
The parameterless constructor leaves _method uninitialized, which may cause GetRuntimeMethod() to return null unexpectedly. Add XML <summary> documentation describing its intended use and consider validating or initializing _method to avoid null references.

src/ScriptEngine/Compilation/StackRuntimeModuleSerializer.cs (1)

22-26: Consider adding exception handling for serialization operations.

While MessagePack typically handles most serialization errors, consider adding try-catch blocks around the MessagePack operations to provide more specific error messages or handle serialization failures gracefully.

Example enhancement:

 public void Serialize(IExecutableModule module, Stream stream)
 {
+    try
+    {
         var serializableModule = SerializableModule.FromExecutableModule(module);
         MessagePackSerializer.Serialize(stream, serializableModule);
+    }
+    catch (Exception ex)
+    {
+        throw new InvalidOperationException($"Failed to serialize module: {ex.Message}", ex);
+    }
 }

Also applies to: 28-32

src/Tests/OneScript.Core.Tests/ScriptCacheServiceTests.cs (1)

101-103: Consider more reliable timing for file modification tests.

Using Thread.Sleep(1) may not be sufficient on fast systems or under load to guarantee different file modification timestamps.

Consider using a more robust approach:

-// Симулируем изменение файла
-System.Threading.Thread.Sleep(1); // Гарантируем другое время модификации
-File.AppendAllText(_testScriptPath, "\n// Изменение");
+// Симулируем изменение файла
+System.Threading.Thread.Sleep(10); // Более надежная задержка
+File.AppendAllText(_testScriptPath, "\n// Изменение");

Alternatively, consider manipulating the file's LastWriteTime directly for more predictable tests.

CACHE_IMPLEMENTATION.md (2)

9-9: Fix markdown formatting issue.

Remove the trailing colon from the heading to comply with markdown standards.

-### Новые файлы:
+### Новые файлы

17-17: Fix markdown formatting issue.

Remove the trailing colon from the heading to comply with markdown standards.

-### Изменения в существующих файлах:
+### Изменения в существующих файлах
src/OneScript.Core/Compilation/ScriptCacheService.cs (1)

159-175: Improve error handling consistency.

The cleanup logic for metadata files is duplicated across multiple exception handlers. Consider extracting this into a helper method to reduce code duplication and improve maintainability.

+        private void CleanupMetadataFile(string metadataFile)
+        {
+            try { File.Delete(metadataFile); } catch { }
+        }

Then replace the duplicated cleanup calls:

-                    try { File.Delete(metadataFile); } catch { }
+                    CleanupMetadataFile(metadataFile);
src/ScriptEngine/Compilation/SerializableModule.cs (1)

494-495: Remove unnecessary empty lines.

Clean up formatting by removing the extra empty line.

         }
-

     }
+     }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 28a4a75 and 57f5cc5.

📒 Files selected for processing (18)
  • CACHE_DEMO.md (1 hunks)
  • CACHE_IMPLEMENTATION.md (1 hunks)
  • src/OneScript.Core/Compilation/Binding/SymbolBinding.cs (1 hunks)
  • src/OneScript.Core/Compilation/CacheMetadata.cs (1 hunks)
  • src/OneScript.Core/Compilation/IModuleSerializer.cs (1 hunks)
  • src/OneScript.Core/Compilation/IScriptCacheService.cs (1 hunks)
  • src/OneScript.Core/Compilation/ScriptCacheService.cs (1 hunks)
  • src/OneScript.Core/OneScript.Core.csproj (1 hunks)
  • src/OneScript.Language/Sources/SourceCode.cs (1 hunks)
  • src/ScriptEngine/Compilation/SerializableModule.cs (1 hunks)
  • src/ScriptEngine/Compilation/StackRuntimeModuleSerializer.cs (1 hunks)
  • src/ScriptEngine/Machine/Contexts/AttachedScriptsFactory.cs (2 hunks)
  • src/ScriptEngine/Machine/Core.cs (2 hunks)
  • src/ScriptEngine/Machine/MachineMethodInfo.cs (1 hunks)
  • src/ScriptEngine/OneScriptCoreOptions.cs (3 hunks)
  • src/ScriptEngine/ScriptEngine.csproj (1 hunks)
  • src/ScriptEngine/ScriptingEngine.cs (4 hunks)
  • src/Tests/OneScript.Core.Tests/ScriptCacheServiceTests.cs (1 hunks)
🧰 Additional context used
🪛 LanguageTool
CACHE_DEMO.md

[uncategorized] ~99-~99: Предлог «с» предполагает употребление прилагательного в родительном или творительном падеже.
Context: ...изации ✅ Готово: - Интеграция кэша с AttachedScriptsFactory - Автоматическое кэширование при использовании `Добавить...

(PREP_C_and_ADJ)

🪛 markdownlint-cli2 (0.17.2)
CACHE_IMPLEMENTATION.md

9-9: Trailing punctuation in heading
Punctuation: ':'

(MD026, no-trailing-punctuation)


17-17: Trailing punctuation in heading
Punctuation: ':'

(MD026, no-trailing-punctuation)

🔇 Additional comments (22)
src/OneScript.Core/Compilation/Binding/SymbolBinding.cs (2)

9-9: LGTM: MessagePack import added for serialization support.

The addition of the MessagePack using directive correctly supports the serialization attributes added to this struct.


14-14: LGTM: Proper MessagePack serialization attributes applied.

The MessagePack attributes are correctly applied:

  • [MessagePackObject] on the struct enables MessagePack serialization
  • [Key(0)] and [Key(1)] provide proper key mapping for the properties
  • Sequential key numbering follows MessagePack best practices

This enables the struct to be serialized as part of the script caching system.

Also applies to: 17-17, 20-20

src/OneScript.Core/Compilation/IModuleSerializer.cs (1)

1-32: LGTM: Well-designed interface for module serialization.

The IModuleSerializer interface provides a clean contract for serializing executable modules with appropriate separation of concerns:

  • Serialize method takes the module and target stream
  • Deserialize method reconstructs the module from stream
  • CanSerialize allows runtime type checking for supported modules

The interface design is flexible and allows for different serialization implementations. The XML documentation in Russian is clear and consistent with the codebase style.

src/ScriptEngine/ScriptingEngine.cs (3)

27-27: LGTM: Proper options field integration.

The _options field is correctly declared as readonly and properly initialized in the constructor, ensuring immutable access to configuration settings throughout the engine's lifetime.

Also applies to: 43-43


99-100: LGTM: Clean caching configuration during initialization.

The caching configuration is properly applied during engine initialization, reading from the options and configuring the attached scripts factory. The Russian comment clearly explains the purpose.


212-219: LGTM: Well-designed public API for runtime caching control.

The SetScriptCachingEnabled method provides a clean public API for dynamically controlling script caching behavior. The implementation correctly delegates to the AttachedScriptsFactory with proper null checking.

The XML documentation in Russian is clear and follows the codebase conventions.

src/ScriptEngine/Compilation/StackRuntimeModuleSerializer.cs (1)

1-39: LGTM: Clean and focused serializer implementation.

The StackRuntimeModuleSerializer provides a well-structured implementation of IModuleSerializer:

  • Proper abstraction: Uses SerializableModule to handle the conversion logic
  • Type safety: CanSerialize method correctly identifies supported module types
  • Clean API: Methods are concise and follow single responsibility principle
  • MessagePack integration: Leverages MessagePack for efficient binary serialization

The implementation correctly delegates serialization complexity to the SerializableModule class, maintaining separation of concerns.

src/ScriptEngine/OneScriptCoreOptions.cs (2)

23-23: LGTM: Consistent configuration option integration.

The script caching configuration follows the established patterns in the class:

  • Proper constant naming convention (SCRIPT_CACHING_KEY)
  • Initialization in constructor with setup method
  • Readonly property for external access

The integration is clean and consistent with other configuration options.

Also applies to: 31-31, 40-40


65-72: LGTM: Sensible default behavior for caching configuration.

The SetupScriptCaching method implements reasonable logic:

  • Enabled by default: Caching is enabled unless explicitly disabled, which is good for performance
  • Case-insensitive: Properly handles "false" in any case
  • Whitespace handling: Trims whitespace before comparison
  • Clear documentation: Russian comment explains the default behavior

The opt-out approach is appropriate for a performance feature like caching.

src/OneScript.Core/Compilation/IScriptCacheService.cs (1)

14-43: Excellent interface design following established patterns.

The interface provides a clean contract for script caching with well-defined methods covering all necessary cache operations. The use of the try-pattern in TryLoadFromCache and comprehensive XML documentation make this interface easy to understand and implement.

src/OneScript.Core/Compilation/CacheMetadata.cs (1)

15-47: Well-designed metadata structure for cache validation.

The class includes all necessary properties for robust cache validation (file modification time, size, runtime version) and uses appropriate data types. The FormatVersion property with default value 1 allows for future format evolution.

src/Tests/OneScript.Core.Tests/ScriptCacheServiceTests.cs (2)

16-48: Comprehensive test setup with proper resource management.

The test class follows good practices with proper setup/teardown, comprehensive cleanup in the Dispose method, and handles file system operations safely with try-catch blocks.


50-158: Excellent test coverage of cache service functionality.

The tests thoroughly cover all aspects of the cache service including validation logic, file creation, cache invalidation, clearing, and behavior when caching is disabled. The use of FluentAssertions makes the test assertions clear and readable.

src/ScriptEngine/Machine/Contexts/AttachedScriptsFactory.cs (3)

57-72: Well-designed public API for cache control.

The new public methods provide clear control over caching behavior while maintaining encapsulation. The documentation is comprehensive and the method signatures are intuitive.


209-229: Excellent cache integration logic with appropriate constraints.

The caching logic is well-implemented with proper conditions - only caching file-based sources without external context. This ensures cache safety while maximizing benefit for the most common use cases.


231-235: Good helper method for source type validation.

The IsFileBasedSource method provides clear logic for determining when caching should be applied, combining both source type and file existence checks.

CACHE_DEMO.md (1)

1-113: Comprehensive and well-structured documentation.

The documentation clearly explains the caching system architecture, integration points, and provides practical testing examples. The step-by-step testing instructions and example code make it easy for developers to understand and verify the caching functionality.

CACHE_IMPLEMENTATION.md (1)

1-59: Well-structured documentation.

The documentation provides a comprehensive overview of the caching implementation, including technical details, usage examples, and limitations. The structure and content are clear and informative.

src/OneScript.Core/Compilation/ScriptCacheService.cs (1)

18-263: Robust cache service implementation.

The cache service provides comprehensive functionality with proper error handling, logging, and resource management. The separation of concerns between metadata and serialized module files is well-designed.

src/ScriptEngine/Compilation/SerializableModule.cs (3)

177-177: Specify culture for boolean parsing.

While boolean parsing is less affected by culture, it's good practice to be explicit about culture usage.

-                    return (BslPrimitiveValue)BslBooleanValue.Create(bool.TryParse(Value, out var boolVal) && boolVal);
+                    return (BslPrimitiveValue)BslBooleanValue.Create(bool.TryParse(Value, out var boolVal) && boolVal);

Actually, boolean parsing doesn't require culture specification, so this is fine as-is.


406-426: Verify method type casting safety.

The explicit cast to MachineMethodInfo with exception throwing is appropriate, but consider whether additional type checking or a more specific exception type would be beneficial.

The current implementation correctly restricts serialization to supported types and provides clear error messages for unsupported scenarios.


26-146: Comprehensive serialization framework.

The SerializableModule class provides a well-structured approach to module serialization with proper MessagePack attributes, version tracking, and bidirectional conversion methods. The implementation correctly handles null values and edge cases.

Comment on lines 61 to 64
public void SetCachingEnabled(bool enabled)
{
((ScriptCacheService)_cacheService).CachingEnabled = enabled;
}
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Abstraction violation in SetCachingEnabled method.

This method also casts to the concrete implementation, which has the same abstraction issues as the constructor.

Consider adding a CachingEnabled property to the IScriptCacheService interface to avoid the cast:

public interface IScriptCacheService
{
    // ... existing methods ...
+   bool CachingEnabled { get; set; }
}

Then update the method:

public void SetCachingEnabled(bool enabled)
{
-   ((ScriptCacheService)_cacheService).CachingEnabled = enabled;
+   _cacheService.CachingEnabled = enabled;
}
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
public void SetCachingEnabled(bool enabled)
{
((ScriptCacheService)_cacheService).CachingEnabled = enabled;
}
public void SetCachingEnabled(bool enabled)
{
_cacheService.CachingEnabled = enabled;
}
🤖 Prompt for AI Agents
In src/ScriptEngine/Machine/Contexts/AttachedScriptsFactory.cs around lines 61
to 64, the SetCachingEnabled method casts _cacheService to the concrete
ScriptCacheService, violating abstraction. To fix this, add a CachingEnabled
property to the IScriptCacheService interface and implement it in
ScriptCacheService. Then update SetCachingEnabled to set the CachingEnabled
property directly on _cacheService without casting.

Comment on lines 224 to 228
if (sourceFileInfo.LastWriteTime != metadata.SourceModifiedTime ||
sourceFileInfo.Length != metadata.SourceSize)
{
return false;
}
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Consider file timestamp precision limitations.

File system timestamp precision varies across platforms and file systems. Consider using a tolerance-based comparison or including file hash validation for more reliable cache invalidation.

                // Проверяем, не изменился ли исходный файл
-               if (sourceFileInfo.LastWriteTime != metadata.SourceModifiedTime ||
+               if (Math.Abs((sourceFileInfo.LastWriteTime - metadata.SourceModifiedTime).TotalSeconds) > 1 ||
                    sourceFileInfo.Length != metadata.SourceSize)
🤖 Prompt for AI Agents
In src/OneScript.Core/Compilation/ScriptCacheService.cs around lines 224 to 228,
the current file timestamp comparison is too strict given file system timestamp
precision limitations. Modify the comparison to allow a small tolerance (e.g., a
few seconds) when comparing LastWriteTime values, or alternatively implement a
file hash check to validate if the file content has changed. This will prevent
false cache invalidations due to minor timestamp differences.

Copilot AI and others added 26 commits July 10, 2025 08:57
…ult and fix abstraction violations

Co-authored-by: nixel2007 <[email protected]>
…nstructor and proper parameter conversion

Co-authored-by: nixel2007 <[email protected]>
Generated test result XML files documenting successful build and test execution on Linux platform. Core functionality tests pass with only minor localization-related failures unrelated to caching implementation:

- OneScript.Core.Tests: 170/171 passed (ScriptCacheServiceTests: 8/8 passed)
- OneScript.DebugProtocol.Test: 8/8 passed
- OneScript.Dynamic.Tests: 40/42 passed
- OneScript.Language.Tests: 160/161 passed

Script pre-compilation caching system verified as fully functional with proper configuration loading and cache service initialization.

Co-authored-by: nixel2007 <[email protected]>
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (2)
.github/workflows/copilot-setup-steps.yml (2)

9-10: Consider matrix or OS-gate if Windows support is later required

The job is pinned to ubuntu-latest.
Given recent Windows-specific failures around opm (#1554), you might eventually need a Windows leg. Either:

  1. Convert to a matrix with both ubuntu and windows, or
  2. Keep Ubuntu default but document the limitation.

No change needed now, just flagging the future portability angle.


37-37: Trim trailing whitespace to satisfy YAML linters

Line 37 contains stray spaces; YAMLlint already flags it.

-37· 
+37
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between d43a159 and ab67ad3.

📒 Files selected for processing (1)
  • .github/workflows/copilot-setup-steps.yml (1 hunks)
🧰 Additional context used
🧠 Learnings (1)
📓 Common learnings
Learnt from: EvilBeaver
PR: EvilBeaver/OneScript#0
File: :0-0
Timestamp: 2024-08-05T18:27:08.563Z
Learning: For each new pull request in the EvilBeaver/OneScript repository, include a poem in Russian.
🪛 YAMLlint (1.37.1)
.github/workflows/copilot-setup-steps.yml

[error] 37-37: trailing spaces

(trailing-spaces)

🔇 Additional comments (1)
.github/workflows/copilot-setup-steps.yml (1)

1-1: 🤖 Поэтический комплимент к PR

Кэш скриптов, что ускорит нам путь,
Словно ветер сквозь строки летит.
Пусть билд-системы не знают уж мук,
А OneScript всё быстрее бежит!

nixel2007 and others added 3 commits July 10, 2025 08:14
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
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.

Пред-компиляция загружаемых сценариев

3 participants