Flutter Engine
The Flutter Engine
Loading...
Searching...
No Matches
persistent_cache_unittests.cc
Go to the documentation of this file.
1// Copyright 2013 The Flutter Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#include "flutter/common/graphics/persistent_cache.h"
6
7#include <memory>
8
9#include "flutter/assets/directory_asset_bundle.h"
10#include "flutter/flow/layers/container_layer.h"
11#include "flutter/flow/layers/layer.h"
12#include "flutter/fml/command_line.h"
13#include "flutter/fml/file.h"
14#include "flutter/fml/log_settings.h"
15#include "flutter/fml/unique_fd.h"
16#include "flutter/shell/common/shell_test.h"
17#include "flutter/shell/common/switches.h"
18#include "flutter/shell/version/version.h"
19#include "flutter/testing/testing.h"
20
21namespace flutter {
22namespace testing {
23
25
27 const std::string& expected) {
28 std::string data_string(reinterpret_cast<const char*>(data->bytes()),
29 data->size());
30 ASSERT_EQ(data_string, expected);
31}
32
33static void ResetAssetManager() {
35 ASSERT_EQ(PersistentCache::GetCacheForProcess()->LoadSkSLs().size(), 0u);
36}
37
40 ASSERT_EQ(shaders.size(), 2u);
41}
42
43TEST_F(PersistentCacheTest, CanLoadSkSLsFromAsset) {
44 // Avoid polluting unit tests output by hiding INFO level logging.
45 fml::LogSettings warning_only = {fml::kLogWarning};
46 fml::ScopedSetLogSettings scoped_set_log_settings(warning_only);
47
48 // The SkSL key is Base32 encoded. "IE" is the encoding of "A" and "II" is the
49 // encoding of "B".
50 //
51 // The SkSL data is Base64 encoded. "eA==" is the encoding of "x" and "eQ=="
52 // is the encoding of "y".
53 const std::string kTestJson =
54 "{\n"
55 " \"data\": {\n"
56 " \"IE\": \"eA==\",\n"
57 " \"II\": \"eQ==\"\n"
58 " }\n"
59 "}\n";
60
61 // Temp dir for the asset.
63
64 auto data = std::make_unique<fml::DataMapping>(
65 std::vector<uint8_t>{kTestJson.begin(), kTestJson.end()});
67
68 // 1st, test that RunConfiguration::InferFromSettings sets the asset manager.
70 auto settings = CreateSettingsForFixture();
71 settings.assets_path = asset_dir.path();
74
75 // 2nd, test that the RunConfiguration constructor sets the asset manager.
76 // (Android is directly calling that constructor without InferFromSettings.)
78 auto asset_manager = std::make_shared<AssetManager>();
79 RunConfiguration config(nullptr, asset_manager);
80 asset_manager->PushBack(std::make_unique<DirectoryAssetBundle>(
81 fml::OpenDirectory(asset_dir.path().c_str(), false,
83 false));
85
86 // 3rd, test the content of the SkSLs in the asset.
87 {
89 ASSERT_EQ(shaders.size(), 2u);
90
91 // Make sure that the 2 shaders are sorted by their keys. Their keys should
92 // be "A" and "B" (decoded from "II" and "IE").
93 if (shaders[0].key->bytes()[0] == 'B') {
94 std::swap(shaders[0], shaders[1]);
95 }
96
97 CheckTextSkData(shaders[0].key, "A");
98 CheckTextSkData(shaders[1].key, "B");
99 CheckTextSkData(shaders[0].value, "x");
100 CheckTextSkData(shaders[1].value, "y");
101 }
102
103 // Cleanup.
105}
106
107TEST_F(PersistentCacheTest, CanRemoveOldPersistentCache) {
109 ASSERT_TRUE(base_dir.fd().is_valid());
110
111 fml::CreateDirectory(base_dir.fd(),
112 {"flutter_engine", GetFlutterEngineVersion(), "skia"},
114
115 constexpr char kOldEngineVersion[] = "old";
116 auto old_created = fml::CreateDirectory(
117 base_dir.fd(), {"flutter_engine", kOldEngineVersion, "skia"},
119 ASSERT_TRUE(old_created.is_valid());
120
123
124 auto engine_dir = fml::OpenDirectoryReadOnly(base_dir.fd(), "flutter_engine");
125 auto current_dir =
127 auto old_dir = fml::OpenDirectoryReadOnly(engine_dir, kOldEngineVersion);
128
129 ASSERT_TRUE(engine_dir.is_valid());
130 ASSERT_TRUE(current_dir.is_valid());
131 ASSERT_FALSE(old_dir.is_valid());
132
133 // Cleanup
135}
136
137TEST_F(PersistentCacheTest, CanPurgePersistentCache) {
139 ASSERT_TRUE(base_dir.fd().is_valid());
140 auto cache_dir = fml::CreateDirectory(
141 base_dir.fd(),
142 {"flutter_engine", GetFlutterEngineVersion(), "skia", GetSkiaVersion()},
146
147 // Generate a dummy persistent cache.
148 fml::DataMapping test_data(std::string("test"));
149 ASSERT_TRUE(fml::WriteAtomically(cache_dir, "test", test_data));
150 auto file = fml::OpenFileReadOnly(cache_dir, "test");
151 ASSERT_TRUE(file.is_valid());
152
153 // Run engine with purge_persistent_cache to remove the dummy cache.
154 auto settings = CreateSettingsForFixture();
155 settings.purge_persistent_cache = true;
156 auto config = RunConfiguration::InferFromSettings(settings);
157 std::unique_ptr<Shell> shell = CreateShell(settings);
158 RunEngine(shell.get(), std::move(config));
159
160 // Verify that the dummy is purged.
161 file = fml::OpenFileReadOnly(cache_dir, "test");
162 ASSERT_FALSE(file.is_valid());
163
164 // Cleanup
166 DestroyShell(std::move(shell));
167}
168
169TEST_F(PersistentCacheTest, PurgeAllowsFutureSkSLCache) {
170 sk_sp<SkData> shader_key = SkData::MakeWithCString("key");
171 sk_sp<SkData> shader_value = SkData::MakeWithCString("value");
172 std::string shader_filename = PersistentCache::SkKeyToFilePath(*shader_key);
173
175 ASSERT_TRUE(base_dir.fd().is_valid());
178
179 // Run engine with purge_persistent_cache and cache_sksl.
180 auto settings = CreateSettingsForFixture();
181 settings.purge_persistent_cache = true;
182 settings.cache_sksl = true;
183 auto config = RunConfiguration::InferFromSettings(settings);
184 std::unique_ptr<Shell> shell = CreateShell(settings);
185 RunEngine(shell.get(), std::move(config));
186 auto persistent_cache = PersistentCache::GetCacheForProcess();
187 ASSERT_EQ(persistent_cache->LoadSkSLs().size(), 0u);
188
189 // Store the cache and verify it's valid.
190 StorePersistentCache(persistent_cache, *shader_key, *shader_value);
191 std::promise<bool> io_flushed;
192 shell->GetTaskRunners().GetIOTaskRunner()->PostTask(
193 [&io_flushed]() { io_flushed.set_value(true); });
194 io_flushed.get_future().get(); // Wait for the IO thread to flush the file.
195 ASSERT_GT(persistent_cache->LoadSkSLs().size(), 0u);
196
197 // Cleanup
199 DestroyShell(std::move(shell));
200}
201
202} // namespace testing
203} // namespace flutter
static sk_sp< SkData > MakeWithCString(const char cstr[])
Definition SkData.cpp:195
static void SetAssetManager(std::shared_ptr< AssetManager > value)
static void SetCacheDirectoryPath(std::string path)
static PersistentCache * GetCacheForProcess()
static constexpr char kAssetFileName[]
std::vector< SkSLCache > LoadSkSLs() const
Load all the SkSL shader caches in the right directory.
static std::string SkKeyToFilePath(const SkData &key)
Specifies all the configuration required by the runtime library to launch the root isolate....
static RunConfiguration InferFromSettings(const Settings &settings, const fml::RefPtr< fml::TaskRunner > &io_worker=nullptr, IsolateLaunchType launch_type=IsolateLaunchType::kNewGroup)
Attempts to infer a run configuration from the settings object. This tries to create a run configurat...
const UniqueFD & fd()
Definition file.h:147
const std::string & path() const
Definition file.h:146
bool is_valid() const
uint8_t value
TEST_F(DisplayListTest, Defaults)
static void CheckTextSkData(const sk_sp< SkData > &data, const std::string &expected)
const char * GetFlutterEngineVersion()
Definition version.cc:11
DEF_SWITCHES_START aot vmservice shared library Name of the *so containing AOT compiled Dart assets for launching the service isolate vm snapshot The VM snapshot data that will be memory mapped as read only SnapshotAssetPath must be present isolate snapshot The isolate snapshot data that will be memory mapped as read only SnapshotAssetPath must be present cache dir Path to the cache directory This is different from the persistent_cache_path in embedder which is used for Skia shader cache icu native lib Path to the library file that exports the ICU data vm service The hostname IP address on which the Dart VM Service should be served If not defaults to or::depending on whether ipv6 is specified vm service A custom Dart VM Service port The default is to pick a randomly available open port disable vm Disable the Dart VM Service The Dart VM Service is never available in release mode disable vm service Disable mDNS Dart VM Service publication Bind to the IPv6 localhost address for the Dart VM Service Ignored if vm service host is set endless trace Enable an endless trace buffer The default is a ring buffer This is useful when very old events need to viewed For during application launch Memory usage will continue to grow indefinitely however Start app with an specific route defined on the framework flutter assets Path to the Flutter assets directory enable service port Allow the VM service to fallback to automatic port selection if binding to a specified port fails trace Trace early application lifecycle Automatically switches to an endless trace buffer trace skia Filters out all Skia trace event categories except those that are specified in this comma separated list dump skp on shader Automatically dump the skp that triggers new shader compilations This is useful for writing custom ShaderWarmUp to reduce jank By this is not enabled to reduce the overhead purge persistent Remove all existing persistent cache This is mainly for debugging purposes such as reproducing the shader compilation jank trace to file
Definition switches.h:201
DEF_SWITCHES_START aot vmservice shared library Name of the *so containing AOT compiled Dart assets for launching the service isolate vm snapshot data
Definition switches.h:41
it will be possible to load the file into Perfetto s trace viewer disable asset Prevents usage of any non test fonts unless they were explicitly Loaded via prefetched default font Indicates whether the embedding started a prefetch of the default font manager before creating the engine run In non interactive keep the shell running after the Dart script has completed enable serial On low power devices with low core running concurrent GC tasks on threads can cause them to contend with the UI thread which could potentially lead to jank This option turns off all concurrent GC activities domain network JSON encoded network policy per domain This overrides the DisallowInsecureConnections switch Embedder can specify whether to allow or disallow insecure connections at a domain level old gen heap size
Definition switches.h:259
fml::UniqueFD OpenFileReadOnly(const fml::UniqueFD &base_directory, const char *path)
Definition file.cc:92
bool RemoveFilesInDirectory(const fml::UniqueFD &directory)
Definition file.cc:102
bool WriteAtomically(const fml::UniqueFD &base_directory, const char *file_name, const Mapping &mapping)
fml::UniqueFD OpenDirectoryReadOnly(const fml::UniqueFD &base_directory, const char *path)
Definition file.cc:97
fml::UniqueFD OpenDirectory(const char *path, bool create_if_necessary, FilePermission permission)
Definition file_posix.cc:97
static fml::UniqueFD CreateDirectory(const fml::UniqueFD &base_directory, const std::vector< std::string > &components, FilePermission permission, size_t index)
Definition file.cc:12
constexpr LogSeverity kLogWarning
Definition log_level.h:14
bool UnlinkFile(const char *path)