forked from swiftlang/swift-package-manager
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathInMemoryPackageCollectionsSearch.swift
361 lines (305 loc) · 16.5 KB
/
InMemoryPackageCollectionsSearch.swift
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
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
/*
This source file is part of the Swift.org open source project
Copyright (c) 2020 Apple Inc. and the Swift project authors
Licensed under Apache License v2.0 with Runtime Library Exception
See http://swift.org/LICENSE.txt for license information
See http://swift.org/CONTRIBUTORS.txt for Swift project authors
*/
import Dispatch
import TSCBasic
import PackageModel
final class InMemoryPackageCollectionsSearch: PackageCollectionsSearch {
let configuration: Configuration
private let packageTrie: Trie<CollectionPackage>
private let targetTrie: Trie<CollectionPackage>
private var cache = [Model.CollectionIdentifier: Model.Collection]()
private let cacheLock = Lock()
private let tokenizer: Tokenizer = WordBoundaryTokenizer()
// For indexing and executing queries
private let queue = DispatchQueue(label: "org.swift.swiftpm.InMemoryPackageCollectionsSearch", attributes: .concurrent)
init(configuration: Configuration = .init()) {
self.configuration = configuration
self.packageTrie = Trie<CollectionPackage>()
self.targetTrie = Trie<CollectionPackage>()
}
func index(collection: Model.Collection,
callback: @escaping (Result<Void, Error>) -> Void) {
self.queue.async {
let group = DispatchGroup()
collection.packages.forEach { package in
group.enter()
self.queue.async {
defer { group.leave() }
let document = CollectionPackage(collection: collection.identifier, package: package.reference.identity)
// This breaks up the URL into tokens because it contains punctuations, so when the
// search query is a repository URL it will need to be tokenized the same way.
// `searchPackages` does this, but not sure this is a good thing? We don't provide
// options to NOT tokenize query string.
self.index(text: package.repository.url, foundIn: document, to: self.packageTrie)
// Index package identity without any transformation for `findPackage`
self.index(text: package.reference.identity.description, foundIn: document, to: self.packageTrie, analyze: false)
if let summary = package.summary {
self.index(text: summary, foundIn: document, to: self.packageTrie)
}
if let keywords = package.keywords {
keywords.forEach {
self.index(text: $0, foundIn: document, to: self.packageTrie)
}
}
package.versions.forEach { version in
self.index(text: version.packageName, foundIn: document, to: self.packageTrie)
version.products.forEach {
self.index(text: $0.name, foundIn: document, to: self.packageTrie)
}
version.targets.forEach {
self.index(text: $0.name, foundIn: document, to: self.packageTrie)
// Target search is not tokenized - it's either exact match or prefix match
self.index(text: $0.name, foundIn: document, to: self.targetTrie, analyze: false)
}
}
}
}
group.notify(queue: self.queue) {
self.cacheLock.withLock {
self.cache[collection.identifier] = collection
}
callback(.success(()))
}
}
}
private func index(text: String, foundIn document: CollectionPackage, to trie: Trie<CollectionPackage>, analyze: Bool = true) {
if analyze {
let tokens = self.analyze(text: text)
tokens.forEach { trie.insert(word: $0, foundIn: document) }
} else {
trie.insert(word: text.lowercased(), foundIn: document)
}
}
func remove(identifier: Model.CollectionIdentifier,
callback: @escaping (Result<Void, Error>) -> Void) {
self.queue.async {
guard let collection = self.cacheLock.withLock({ self.cache.removeValue(forKey: identifier) }) else {
return callback(.success(()))
}
let group = DispatchGroup()
collection.packages.forEach { package in
group.enter()
self.queue.async {
defer { group.leave() }
let document = CollectionPackage(collection: identifier, package: package.reference.identity)
self.packageTrie.remove(document: document)
self.targetTrie.remove(document: document)
}
}
group.notify(queue: self.queue) {
callback(.success(()))
}
}
}
func findPackage(identifier: PackageIdentity,
collectionIdentifiers: [Model.CollectionIdentifier]? = nil,
callback: @escaping (Result<Model.PackageSearchResult.Item, Error>) -> Void) {
self.queue.async {
let documents: Set<CollectionPackage>
do {
documents = try self.packageTrie.find(word: identifier.description)
} catch { // This includes `NotFoundError`
return callback(.failure(error))
}
let collectionIdentifiers: Set<Model.CollectionIdentifier>? = collectionIdentifiers.flatMap { Set($0) }
let collections = documents.filter { collectionIdentifiers?.contains($0.collection) ?? true }
.compactMap { collectionPackage in self.cacheLock.withLock { self.cache[collectionPackage.collection] } }
// Sort collections by processing date so the latest metadata is first
.sorted(by: { lhs, rhs in lhs.lastProcessedAt > rhs.lastProcessedAt })
guard let package = collections.compactMap({ $0.packages.first { $0.reference.identity == identifier } }).first else {
return callback(.failure(NotFoundError("\(identifier)")))
}
callback(.success(.init(package: package, collections: collections.map { $0.identifier })))
}
}
func searchPackages(identifiers: [Model.CollectionIdentifier]? = nil,
query: String,
callback: @escaping (Result<Model.PackageSearchResult, Error>) -> Void) {
self.queue.async {
// Clean and break up query string into tokens
let queryTokens = self.analyze(text: query)
var queryResults = [String: Result<Set<CollectionPackage>, Error>]()
let queryResultsLock = Lock()
let group = DispatchGroup()
queryTokens.forEach { token in
group.enter()
self.queue.async {
defer { group.leave() }
do {
let matches = try self.packageTrie.find(word: token)
queryResultsLock.withLock { queryResults[token] = .success(matches) }
} catch {
queryResultsLock.withLock { queryResults[token] = .failure(error) }
}
}
}
group.notify(queue: self.queue) {
let errors = queryResults.values.compactMap { $0.failure }.filter { !($0 is NotFoundError) }
guard errors.isEmpty else {
return callback(.failure(MultipleErrors(errors)))
}
// We only want `CollectionPackage`s that match *all* tokens
let collectionIdentifiers: Set<Model.CollectionIdentifier>? = identifiers.flatMap { Set($0) }
let matchingCollectionPackages = queryResults.values
.compactMap { $0.success }
.reduce(into: [CollectionPackage: Int]()) { result, documents in
// Count matches for each `CollectionPackage`
documents.forEach {
result[$0] = (result[$0] ?? 0) + 1
}
}
.filter { collectionPackage, score in
// Qualified results must contain all query tokens
score == queryTokens.count && collectionIdentifiers?.contains(collectionPackage.collection) ?? true
}
.keys
// Construct the result
let packageCollections = matchingCollectionPackages
.reduce(into: [PackageIdentity: (package: Model.Package, collections: Set<Model.CollectionIdentifier>)]()) { result, collectionPackage in
var entry = result.removeValue(forKey: collectionPackage.package)
if entry == nil {
guard let package = self.cacheLock.withLock({
self.cache[collectionPackage.collection].flatMap { collection in
collection.packages.first { $0.reference.identity == collectionPackage.package }
}
}) else {
return
}
entry = (package, .init())
}
if var entry = entry {
entry.collections.insert(collectionPackage.collection)
result[collectionPackage.package] = entry
}
}
let result = Model.PackageSearchResult(items: packageCollections.map { entry in
.init(package: entry.value.package, collections: Array(entry.value.collections))
})
callback(.success(result))
}
}
}
func searchTargets(identifiers: [Model.CollectionIdentifier]? = nil,
query: String,
type: Model.TargetSearchType,
callback: @escaping (Result<Model.TargetSearchResult, Error>) -> Void) {
self.queue.async {
let matches: [String: Set<CollectionPackage>]
do {
switch type {
case .exactMatch:
matches = [query.lowercased(): try self.targetTrie.find(word: query)]
case .prefix:
matches = try self.targetTrie.findWithPrefix(query)
}
} catch is NotFoundError {
matches = [:]
} catch {
return callback(.failure(error))
}
let collectionIdentifiers: Set<Model.CollectionIdentifier>? = identifiers.flatMap { Set($0) }
var packageCollections = [PackageIdentity: (package: Model.Package, collections: Set<Model.CollectionIdentifier>)]()
var targetPackageVersions = [Model.Target: [PackageIdentity: Set<Model.TargetListResult.PackageVersion>]]()
// Group `CollectionPackage`s by packages
// For each matching target name, find the containing package version(s)
matches.forEach { targetName, collectionPackages in
collectionPackages.filter { collectionIdentifiers?.contains($0.collection) ?? true }.forEach { collectionPackage in
var packageEntry = packageCollections.removeValue(forKey: collectionPackage.package)
if packageEntry == nil {
guard let package = self.cacheLock.withLock({
self.cache[collectionPackage.collection].flatMap { collection in
collection.packages.first { $0.reference.identity == collectionPackage.package }
}
}) else {
return
}
packageEntry = (package, .init())
}
if var packageEntry = packageEntry {
packageEntry.collections.insert(collectionPackage.collection)
packageCollections[collectionPackage.package] = packageEntry
packageEntry.package.versions.forEach { version in
let targets = version.targets.filter { $0.name.lowercased() == targetName }
targets.forEach { target in
var targetEntry = targetPackageVersions.removeValue(forKey: target) ?? [:]
var targetPackageEntry = targetEntry.removeValue(forKey: packageEntry.package.reference.identity) ?? .init()
targetPackageEntry.insert(.init(version: version.version, packageName: version.packageName))
targetEntry[packageEntry.package.reference.identity] = targetPackageEntry
targetPackageVersions[target] = targetEntry
}
}
}
}
}
let result = Model.TargetSearchResult(items: targetPackageVersions.map { target, packageVersions in
let targetPackages: [Model.TargetListItem.Package] = packageVersions.compactMap { reference, versions in
guard let packageEntry = packageCollections[reference] else {
return nil
}
return Model.TargetListItem.Package(
repository: packageEntry.package.repository,
summary: packageEntry.package.summary,
versions: Array(versions).sorted(by: >),
collections: Array(packageEntry.collections)
)
}
return Model.TargetListItem(target: target, packages: targetPackages)
})
callback(.success(result))
}
}
func analyze(text: String) -> [String] {
var tokens = self.tokenizer.tokenize(text: text)
tokens = TokenFilters.lowercase(tokens: tokens)
tokens = TokenFilters.stopwords(tokens: tokens, stopwords: self.configuration.stopwords)
return tokens
}
private struct CollectionPackage: Hashable, CustomStringConvertible {
let collection: Model.CollectionIdentifier
let package: PackageIdentity
var description: String {
"\(collection): \(package)"
}
}
struct Configuration {
// https://www.link-assistant.com/seo-stop-words.html
static let stopwords: Set<String> = [
"a", "am", "an", "and", "also", "are", "b", "be", "been", "being", "but",
"c", "can", "cannot", "could", "d", "did", "do", "does", "doing", "done", "e",
"f", "for", "from", "g", "h", "had", "has", "have", "he", "her", "hers", "him", "his", "how", "however",
"i", "if", "in", "is", "it", "its", "j", "just", "k", "l", "let",
"m", "may", "me", "might", "mine", "must", "my", "n", "not", "o", "of", "on", "or", "our", "ours",
"p", "q", "r", "re", "s", "shall", "she", "should", "so",
"t", "that", "the", "their", "theirs", "them", "then", "there", "these", "they", "this", "those", "to", "too",
"u", "un", "us", "v",
"w", "was", "we", "were", "what", "when", "where", "which", "while", "who", "whom", "whose", "why", "will", "with", "would",
"x", "y", "yes", "yet", "you", "your", "yours", "z"
]
var stopwords: Set<String>
init(stopwords: Set<String>? = nil) {
self.stopwords = stopwords ?? Self.stopwords
}
}
}
protocol Tokenizer {
func tokenize(text: String) -> [String]
}
struct WordBoundaryTokenizer: Tokenizer {
func tokenize(text: String) -> [String] {
// Split on any character that is not a letter or a number
text.split { !$0.isLetter && !$0.isNumber }.map(String.init)
}
}
enum TokenFilters {
static func lowercase(tokens: [String]) -> [String] {
tokens.map { $0.lowercased() }
}
static func stopwords(tokens: [String], stopwords: Set<String> = []) -> [String] {
tokens.filter { !stopwords.contains($0) }
}
}