Repository navigation
Expand file tree
/
Copy pathColdProfileCopy.vb
More file actions
298 lines (269 loc) · 13.2 KB
/
Copy pathColdProfileCopy.vb
File metadata and controls
298 lines (269 loc) · 13.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
Imports System
Imports System.Collections.Generic
Imports System.IO
Imports System.Linq
Imports System.Threading.Tasks
''' <summary>
''' Whole-directory copy for a CLOSED browser profile. Never merges database generations.
''' The caller must hold the account lease and have observed BrowserProcessExited.
''' A failed copy leaves the destination unchanged. Publication uses two renames with rollback;
''' this is not a filesystem transaction (a power loss can leave .previous beside the target).
''' </summary>
Friend NotInheritable Class ColdProfileCopy
Private Class CopyItem
Public Property SourcePath As String
Public Property DestinationPath As String
End Class
Public Shared ReadOnly SkipFolderNames As New HashSet(Of String)(StringComparer.OrdinalIgnoreCase) From {
"Cache",
"Code Cache",
"GPUCache",
"GPUPersistentCache",
"ShaderCache",
"GrShaderCache",
"DawnCache",
"DawnGraphiteCache",
"DawnWebGPUCache",
"GraphiteDawnCache",
"Crashpad",
"BrowserMetrics",
"BrowserMetrics-spare",
"component_crx_cache",
"extensions_crx_cache",
"OptimizationGuidePredictionModels",
"optimization_guide_hint_cache_store",
"AutofillAiModelCache",
"Safe Browsing",
"Subresource Filter",
"CacheStorage",
"ScriptCache",
"blob_storage"
}
Private Shared ReadOnly SkipExactFileNames As New HashSet(Of String)(StringComparer.OrdinalIgnoreCase) From {
"LOCK",
".active_session",
"DevToolsActivePort"
}
Public Shared Function HasData(directoryPath As String) As Boolean
If Not Directory.Exists(directoryPath) Then Return False
' Conservatively preserve ANY existing state, even a small/empty-looking database.
Return Directory.EnumerateFileSystemEntries(directoryPath).Any()
End Function
''' <summary>
''' Verifica se la cartella sorgente contiene file essenziali modificati dopo la data di baseline del target master.
''' Se non vi sono modifiche, la sincronizzazione via rete può essere saltata completamente (0 ms di I/O).
''' </summary>
Public Shared Function HasModifications(source As String, target As String) As Boolean
If Not Directory.Exists(source) Then Return False
If Not Directory.Exists(target) Then Return True
Dim baselineUtc = Directory.GetLastWriteTimeUtc(target)
Dim previous = target & ".previous"
If Directory.Exists(previous) Then
Dim prevTime = Directory.GetLastWriteTimeUtc(previous)
If prevTime > baselineUtc Then baselineUtc = prevTime
End If
Return CheckDirectoryModified(source, "", baselineUtc)
End Function
Private Shared Function CheckDirectoryModified(currentDir As String, relative As String, baselineUtc As DateTime) As Boolean
If Not Directory.Exists(currentDir) Then Return False
For Each entry In Directory.EnumerateFileSystemEntries(currentDir)
Dim name = Path.GetFileName(entry)
Dim childRelative = If(relative.Length = 0, name, relative & "/" & name)
If ShouldSkip(childRelative) Then Continue For
If Directory.Exists(entry) Then
If CheckDirectoryModified(entry, childRelative, baselineUtc) Then Return True
Else
If File.GetLastWriteTimeUtc(entry) > baselineUtc Then Return True
End If
Next
Return False
End Function
Public Shared Sub RecoverInterruptedPublication(target As String)
Dim previous = target & ".previous"
If Not Directory.Exists(target) AndAlso Directory.Exists(previous) Then
Directory.Move(previous, target)
End If
' Bonifica eventuali directory temporanee orfane (.incoming-* o .trash-*)
Try
Dim parentDir = Path.GetDirectoryName(target)
If Directory.Exists(parentDir) Then
Dim targetName = Path.GetFileName(target)
For Each orphan In Directory.EnumerateDirectories(parentDir, targetName & ".*")
If orphan.Contains(".incoming-") OrElse orphan.Contains(".trash-") Then
Try
Directory.Delete(orphan, recursive:=True)
Catch
End Try
End If
Next
End If
Catch
End Try
End Sub
Public Shared Async Function SeedIfEmptyAsync(source As String, target As String) As Task(Of Boolean)
RecoverInterruptedPublication(target)
If HasData(target) Then Return True
RecoverInterruptedPublication(source)
If Not HasData(source) Then
Directory.CreateDirectory(target)
Return True
End If
Return Await PublishAsync(source, target)
End Function
Public Shared Function PublishAsync(source As String, target As String) As Task(Of Boolean)
Return Task.Run(Function() Publish(source, target))
End Function
Private Shared Function Publish(source As String, target As String) As Boolean
Dim incoming As String = Nothing
Dim previous As String = Nothing
Dim trash As String = Nothing
Try
source = Path.GetFullPath(source).TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar)
target = Path.GetFullPath(target).TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar)
If source.Equals(target, StringComparison.OrdinalIgnoreCase) OrElse
source.StartsWith(target & Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase) OrElse
target.StartsWith(source & Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase) Then
Throw New IOException("Source and destination profiles overlap.")
End If
If Not Directory.Exists(source) Then Return False
RejectReparsePoint(source)
Directory.CreateDirectory(Path.GetDirectoryName(target))
RecoverInterruptedPublication(target)
If Directory.Exists(target) Then RejectReparsePoint(target)
previous = target & ".previous"
incoming = target & ".incoming-" & Guid.NewGuid().ToString("N")
CopyTree(source, incoming, "")
' Do not touch the old destination until EVERY required file has been copied.
' On network/SMB shares, avoid synchronous in-place recursive deletion of .previous
' before moving, as it can fail with ERROR_ACCESS_DENIED or stall.
' Rename .previous to .trash-<guid> instantly, rotate target -> previous and incoming -> target.
If Directory.Exists(previous) Then
RejectReparsePoint(previous)
trash = target & ".trash-" & Guid.NewGuid().ToString("N")
SafeMoveDirectory(previous, trash)
End If
If Directory.Exists(target) Then SafeMoveDirectory(target, previous)
Try
SafeMoveDirectory(incoming, target)
Catch
If Not Directory.Exists(target) AndAlso Directory.Exists(previous) Then
Try
SafeMoveDirectory(previous, target)
Catch
End Try
End If
Throw
End Try
' Bonifica asincrona non bloccante della cartella .trash-* per non trattenere la procedura di uscita
If trash IsNot Nothing Then
Dim trashToPurge = trash
Task.Run(Sub()
Try
If Directory.Exists(trashToPurge) Then
Directory.Delete(trashToPurge, recursive:=True)
End If
Catch
End Try
End Sub)
End If
' Retain .previous for manual recovery; it is not proof of a valid login.
Return True
Catch ex As Exception
AppLogger.LogSync($"Cold profile copy failed; no partial database is published: {ex.Message}")
Return False
Finally
If incoming IsNot Nothing AndAlso Directory.Exists(incoming) Then
Try
Directory.Delete(incoming, recursive:=True)
Catch
' A leftover .incoming-* directory is NEVER selected as a profile.
End Try
End If
End Try
End Function
Private Shared Sub SafeMoveDirectory(sourceDir As String, destDir As String, Optional maxRetries As Integer = 3)
Dim lastEx As Exception = Nothing
For attempt As Integer = 1 To maxRetries
Try
Directory.Move(sourceDir, destDir)
Return
Catch ex As Exception
lastEx = ex
If attempt < maxRetries Then
Threading.Thread.Sleep(150 * attempt)
End If
End Try
Next
If lastEx IsNot Nothing Then Throw lastEx
End Sub
Private Shared Sub CopyTree(source As String, target As String, relative As String)
Dim directoriesToCreate As New HashSet(Of String)(StringComparer.OrdinalIgnoreCase)
Dim filesToCopy As New List(Of CopyItem)()
CollectEntries(source, target, relative, directoriesToCreate, filesToCopy)
' Pre-creazione di tutte le cartelle della gerarchia nel target incoming
For Each folderPath As String In directoriesToCreate
Directory.CreateDirectory(folderPath)
Next
' Copia parallela con grado di concorrenza limitato (4 copie concorrenti per account).
' L'uso di File.Copy sfrutta direttamente Win32 CopyFileEx, che garantisce conservazione nativa
' dei timestamp ed eccellente rendimento su condivisioni SMB senza roundtrip I/O separati.
Dim po As New ParallelOptions With {.MaxDegreeOfParallelism = 4}
Parallel.ForEach(filesToCopy, po, Sub(item)
File.Copy(item.SourcePath, item.DestinationPath, overwrite:=True)
End Sub)
End Sub
Private Shared Sub CollectEntries(sourceDir As String, targetDir As String, relative As String,
directoriesToCreate As HashSet(Of String), filesToCopy As List(Of CopyItem))
RejectReparsePoint(sourceDir)
directoriesToCreate.Add(targetDir)
For Each entry In Directory.EnumerateFileSystemEntries(sourceDir)
Dim name = Path.GetFileName(entry)
Dim childRelative = If(relative.Length = 0, name, relative & "/" & name)
If ShouldSkip(childRelative) Then Continue For
RejectReparsePoint(entry)
Dim destination = Path.Combine(targetDir, name)
If Directory.Exists(entry) Then
CollectEntries(entry, destination, childRelative, directoriesToCreate, filesToCopy)
Else
filesToCopy.Add(New CopyItem With {.SourcePath = entry, .DestinationPath = destination})
End If
Next
End Sub
Private Shared Sub RejectReparsePoint(value As String)
If (File.GetAttributes(value) And FileAttributes.ReparsePoint) <> 0 Then
Throw New IOException("Profile copy refuses symbolic links/reparse points: " & value)
End If
End Sub
Friend Shared Function ShouldSkip(relative As String) As Boolean
If String.IsNullOrWhiteSpace(relative) Then Return False
Dim normalized = relative.Replace("\"c, "/"c).Trim("/"c)
Dim parts = normalized.Split("/"c)
Dim name = parts(parts.Length - 1)
' Check lock, session or temporary singleton files
If SkipExactFileNames.Contains(name) OrElse
name.StartsWith("Singleton", StringComparison.OrdinalIgnoreCase) OrElse
name.EndsWith(".lock", StringComparison.OrdinalIgnoreCase) OrElse
name.EndsWith(".dmp", StringComparison.OrdinalIgnoreCase) OrElse
name.EndsWith(".pma", StringComparison.OrdinalIgnoreCase) OrElse
name.EndsWith(".old", StringComparison.OrdinalIgnoreCase) OrElse
name.EndsWith(".tmp", StringComparison.OrdinalIgnoreCase) Then
Return True
End If
' If ANY folder in the relative path is a cache/junk folder, skip it
For Each part In parts
If SkipFolderNames.Contains(part) Then Return True
Next
' Compatibility for legacy relative paths (e.g., EBWebView/Default/Cache)
Dim legacyPrefixes = {"EBWebView/Crashpad", "EBWebView/ShaderCache", "EBWebView/GrShaderCache",
"EBWebView/Default/Cache", "EBWebView/Default/Code Cache", "EBWebView/Default/GPUCache"}
For Each prefix In legacyPrefixes
If normalized.Equals(prefix, StringComparison.OrdinalIgnoreCase) OrElse
normalized.StartsWith(prefix & "/", StringComparison.OrdinalIgnoreCase) Then
Return True
End If
Next
' Cookies, Local State, SQLite journals/WAL, IndexedDB, Local/Session Storage,
' Service Worker Database (worker registrations) and Preferences are retained together, without size heuristics.
Return False
End Function
End Class