Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(243)

Side by Side Diff: pkg/barback/lib/src/package_graph.dart

Issue 187263003: Move Barback to a more thoroughly push-based model. (Closed) Base URL: https://dart.googlecode.com/svn/branches/bleeding_edge/dart
Patch Set: code review Created 6 years, 9 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch | Annotate | Revision Log
« no previous file with comments | « pkg/barback/lib/src/group_runner.dart ('k') | pkg/barback/lib/src/phase.dart » ('j') | no next file with comments »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
OLDNEW
1 // Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file 1 // Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file
2 // for details. All rights reserved. Use of this source code is governed by a 2 // for details. All rights reserved. Use of this source code is governed by a
3 // BSD-style license that can be found in the LICENSE file. 3 // BSD-style license that can be found in the LICENSE file.
4 4
5 library barback.package_graph; 5 library barback.package_graph;
6 6
7 import 'dart:async'; 7 import 'dart:async';
8 import 'dart:collection';
8 9
9 import 'asset_cascade.dart'; 10 import 'asset_cascade.dart';
10 import 'asset_id.dart'; 11 import 'asset_id.dart';
11 import 'asset_node.dart'; 12 import 'asset_node.dart';
12 import 'asset_set.dart'; 13 import 'asset_set.dart';
13 import 'build_result.dart'; 14 import 'build_result.dart';
14 import 'errors.dart'; 15 import 'errors.dart';
15 import 'log.dart'; 16 import 'log.dart';
16 import 'package_provider.dart'; 17 import 'package_provider.dart';
17 import 'transformer.dart'; 18 import 'transformer.dart';
18 import 'utils.dart'; 19 import 'utils.dart';
19 20
20 /// The collection of [AssetCascade]s for an entire application. 21 /// The collection of [AssetCascade]s for an entire application.
21 /// 22 ///
22 /// This tracks each package's [AssetCascade] and routes asset requests between 23 /// This tracks each package's [AssetCascade] and routes asset requests between
23 /// them. 24 /// them.
24 class PackageGraph { 25 class PackageGraph {
25 /// The provider that exposes asset and package information. 26 /// The provider that exposes asset and package information.
26 final PackageProvider provider; 27 final PackageProvider provider;
27 28
28 /// The [AssetCascade] for each package. 29 /// The [AssetCascade] for each package.
29 final _cascades = <String, AssetCascade>{}; 30 final _cascades = <String, AssetCascade>{};
30 31
31 /// The current [BuildResult] for each package's [AssetCascade].
32 ///
33 /// The result for a given package will be `null` if that [AssetCascade] is
34 /// actively building.
35 final _cascadeResults = <String, BuildResult>{};
36
37 /// A stream that emits a [BuildResult] each time the build is completed, 32 /// A stream that emits a [BuildResult] each time the build is completed,
38 /// whether or not it succeeded. 33 /// whether or not it succeeded.
39 /// 34 ///
40 /// This will emit a result only once every package's [AssetCascade] has 35 /// This will emit a result only once every package's [AssetCascade] has
41 /// finished building. 36 /// finished building.
42 /// 37 ///
43 /// If an unexpected error in barback itself occurs, it will be emitted 38 /// If an unexpected error in barback itself occurs, it will be emitted
44 /// through this stream's error channel. 39 /// through this stream's error channel.
45 Stream<BuildResult> get results => _resultsController.stream; 40 Stream<BuildResult> get results => _resultsController.stream;
46 final _resultsController = new StreamController<BuildResult>.broadcast(); 41 final _resultsController =
42 new StreamController<BuildResult>.broadcast(sync: true);
47 43
48 /// A stream that emits any errors from the graph or the transformers. 44 /// A stream that emits any errors from the graph or the transformers.
49 /// 45 ///
50 /// This emits errors as they're detected. If an error occurs in one part of 46 /// This emits errors as they're detected. If an error occurs in one part of
51 /// the graph, unrelated parts will continue building. 47 /// the graph, unrelated parts will continue building.
52 /// 48 ///
53 /// This will not emit programming errors from barback itself. Those will be 49 /// This will not emit programming errors from barback itself. Those will be
54 /// emitted through the [results] stream's error channel. 50 /// emitted through the [results] stream's error channel.
55 Stream<BarbackException> get errors => _errors; 51 Stream<BarbackException> get errors => _errors;
56 Stream<BarbackException> _errors; 52 Stream<BarbackException> _errors;
57 53
58 /// The stream of [LogEntry] objects used to report transformer log entries. 54 /// The stream of [LogEntry] objects used to report transformer log entries.
59 Stream<LogEntry> get log => _logController.stream; 55 Stream<LogEntry> get log => _logController.stream;
60 final _logController = new StreamController<LogEntry>.broadcast(sync: true); 56 final _logController = new StreamController<LogEntry>.broadcast(sync: true);
61 57
58 /// Whether [this] is dirty and still has more processing to do.
59 bool get _isDirty => _cascades.values.any((cascade) => cascade.isDirty);
60
61 /// Whether a [BuildResult] is scheduled to be emitted on [results] (see
62 /// [_tryScheduleResult]).
63 bool _resultScheduled = false;
64
65 /// The most recent [BuildResult] emitted on [results].
66 BuildResult _lastResult;
67
68 // TODO(nweiz): This can have bogus errors if an error is created and resolved
69 // in the space of one build.
70 /// The errors that have occurred since the current build started.
71 ///
72 /// This will be empty if no build is occurring.
73 final _accumulatedErrors = new Queue<BarbackException>();
74
62 /// The most recent error emitted from a cascade's result stream. 75 /// The most recent error emitted from a cascade's result stream.
63 /// 76 ///
64 /// This is used to pipe an unexpected error from a build to the resulting 77 /// This is used to pipe an unexpected error from a build to the resulting
65 /// [Future] returned by [getAllAssets]. 78 /// [Future] returned by [getAllAssets].
66 var _lastUnexpectedError; 79 var _lastUnexpectedError;
67 80
68 /// The stack trace for [_lastUnexpectedError]. 81 /// The stack trace for [_lastUnexpectedError].
69 StackTrace _lastUnexpectedErrorTrace; 82 StackTrace _lastUnexpectedErrorTrace;
70 83
71 /// Creates a new [PackageGraph] that will transform assets in all packages 84 /// Creates a new [PackageGraph] that will transform assets in all packages
72 /// made available by [provider]. 85 /// made available by [provider].
73 PackageGraph(this.provider) { 86 PackageGraph(this.provider) {
74 _inErrorZone(() { 87 _inErrorZone(() {
75 for (var package in provider.packages) { 88 for (var package in provider.packages) {
76 var cascade = new AssetCascade(this, package); 89 var cascade = new AssetCascade(this, package);
77 // The initial result for each cascade is "success" since the cascade
78 // doesn't start building until some source in that graph is updated.
79 _cascadeResults[package] = new BuildResult.success();
80 _cascades[package] = cascade; 90 _cascades[package] = cascade;
81 cascade.onDirty.listen((_) {
82 _cascadeResults[package] = null;
83 });
84
85 cascade.onLog.listen(_onLog); 91 cascade.onLog.listen(_onLog);
86 _handleResults(cascade); 92 cascade.onDone.listen((_) => _tryScheduleResult());
87 } 93 }
88 94
89 _errors = mergeStreams(_cascades.values.map((cascade) => cascade.errors), 95 _errors = mergeStreams(_cascades.values.map((cascade) => cascade.errors),
90 broadcast: true); 96 broadcast: true);
97 _errors.listen(_accumulatedErrors.add);
91 }); 98 });
92 } 99 }
93 100
94 /// Gets the asset node identified by [id]. 101 /// Gets the asset node identified by [id].
95 /// 102 ///
96 /// If [id] is for a generated or transformed asset, this will wait until it 103 /// If [id] is for a generated or transformed asset, this will wait until it
97 /// has been created and return it. This means that the returned asset will 104 /// has been created and return it. This means that the returned asset will
98 /// always be [AssetState.AVAILABLE]. 105 /// always be [AssetState.AVAILABLE].
99 /// 106 ///
100 /// If the asset cannot be found, returns null. 107 /// If the asset cannot be found, returns null.
(...skipping 11 matching lines...) Expand all
112 /// returned future will complete with an error if the build is not 119 /// returned future will complete with an error if the build is not
113 /// successful. 120 /// successful.
114 /// 121 ///
115 /// Any transforms using [LazyTransformer]s will be forced to generate 122 /// Any transforms using [LazyTransformer]s will be forced to generate
116 /// concrete outputs, and those outputs will be returned. 123 /// concrete outputs, and those outputs will be returned.
117 Future<AssetSet> getAllAssets() { 124 Future<AssetSet> getAllAssets() {
118 for (var cascade in _cascades.values) { 125 for (var cascade in _cascades.values) {
119 _inErrorZone(() => cascade.forceAllTransforms()); 126 _inErrorZone(() => cascade.forceAllTransforms());
120 } 127 }
121 128
122 if (_cascadeResults.values.contains(null)) { 129 if (_isDirty) {
123 // A build is still ongoing, so wait for it to complete and try again. 130 // A build is still ongoing, so wait for it to complete and try again.
124 return results.first.then((_) => getAllAssets()); 131 return results.first.then((_) => getAllAssets());
125 } 132 }
126 133
127 // If an unexpected error occurred, complete with that. 134 // If an unexpected error occurred, complete with that.
128 if (_lastUnexpectedError != null) { 135 if (_lastUnexpectedError != null) {
129 var error = _lastUnexpectedError; 136 var error = _lastUnexpectedError;
130 _lastUnexpectedError = null; 137 _lastUnexpectedError = null;
131 return new Future.error(error, _lastUnexpectedErrorTrace); 138 return new Future.error(error, _lastUnexpectedErrorTrace);
132 } 139 }
133 140
134 // If the build completed with an error, complete the future with it. 141 // If the last build completed with an error, complete the future with it.
135 var result = new BuildResult.aggregate(_cascadeResults.values); 142 if (!_lastResult.succeeded) {
136 if (!result.succeeded) { 143 return new Future.error(BarbackException.aggregate(_lastResult.errors));
137 return new Future.error(BarbackException.aggregate(result.errors));
138 } 144 }
139 145
140 // Otherwise, return all of the final output assets. 146 // Otherwise, return all of the final output assets.
141 var assets = unionAll(_cascades.values.map( 147 var assets = unionAll(_cascades.values.map(
142 (cascade) => cascade.availableOutputs.toSet())); 148 (cascade) => cascade.availableOutputs.toSet()));
143 149
144 return new Future.value(new AssetSet.from(assets)); 150 return new Future.value(new AssetSet.from(assets));
145 } 151 }
146 152
147 /// Adds [sources] to the graph's known set of source assets. 153 /// Adds [sources] to the graph's known set of source assets.
148 /// 154 ///
149 /// Begins applying any transforms that can consume any of the sources. If a 155 /// Begins applying any transforms that can consume any of the sources. If a
150 /// given source is already known, it is considered modified and all 156 /// given source is already known, it is considered modified and all
151 /// transforms that use it will be re-applied. 157 /// transforms that use it will be re-applied.
152 void updateSources(Iterable<AssetId> sources) { 158 void updateSources(Iterable<AssetId> sources) {
153 groupBy(sources, (id) => id.package).forEach((package, ids) { 159 groupBy(sources, (id) => id.package).forEach((package, ids) {
154 var cascade = _cascades[package]; 160 var cascade = _cascades[package];
155 if (cascade == null) throw new ArgumentError("Unknown package $package."); 161 if (cascade == null) throw new ArgumentError("Unknown package $package.");
156 _inErrorZone(() => cascade.updateSources(ids)); 162 _inErrorZone(() => cascade.updateSources(ids));
157 }); 163 });
164
165 // It's possible for adding sources not to cause any processing. The user
166 // still expects there to be a build, though, so we emit one immediately.
167 _tryScheduleResult();
158 } 168 }
159 169
160 /// Removes [removed] from the graph's known set of source assets. 170 /// Removes [removed] from the graph's known set of source assets.
161 void removeSources(Iterable<AssetId> sources) { 171 void removeSources(Iterable<AssetId> sources) {
162 groupBy(sources, (id) => id.package).forEach((package, ids) { 172 groupBy(sources, (id) => id.package).forEach((package, ids) {
163 var cascade = _cascades[package]; 173 var cascade = _cascades[package];
164 if (cascade == null) throw new ArgumentError("Unknown package $package."); 174 if (cascade == null) throw new ArgumentError("Unknown package $package.");
165 _inErrorZone(() => cascade.removeSources(ids)); 175 _inErrorZone(() => cascade.removeSources(ids));
166 }); 176 });
177
178 // It's possible for removing sources not to cause any processing. The user
179 // still expects there to be a build, though, so we emit one immediately.
180 _tryScheduleResult();
167 } 181 }
168 182
169 void updateTransformers(String package, 183 void updateTransformers(String package,
170 Iterable<Iterable<Transformer>> transformers) { 184 Iterable<Iterable<Transformer>> transformers) {
171 _inErrorZone(() => _cascades[package].updateTransformers(transformers)); 185 _inErrorZone(() => _cascades[package].updateTransformers(transformers));
186
187 // It's possible for updating transformers not to cause any processing. The
188 // user still expects there to be a build, though, so we emit one
189 // immediately.
190 _tryScheduleResult();
172 } 191 }
173 192
174 /// A handler for a log entry from an [AssetCascade]. 193 /// A handler for a log entry from an [AssetCascade].
175 void _onLog(LogEntry entry) { 194 void _onLog(LogEntry entry) {
195 if (entry.level == LogLevel.ERROR) {
196 // TODO(nweiz): keep track of stack chain.
197 _accumulatedErrors.add(
198 new TransformerException(entry.transform, entry.message, null));
199 }
200
176 if (_logController.hasListener) { 201 if (_logController.hasListener) {
177 _logController.add(entry); 202 _logController.add(entry);
178 } else if (entry.level != LogLevel.FINE) { 203 } else if (entry.level != LogLevel.FINE) {
179 // No listeners, so just print entry. 204 // No listeners, so just print entry.
180 var buffer = new StringBuffer(); 205 var buffer = new StringBuffer();
181 buffer.write("[${entry.level} ${entry.transform}] "); 206 buffer.write("[${entry.level} ${entry.transform}] ");
182 207
183 if (entry.span != null) { 208 if (entry.span != null) {
184 buffer.write(entry.span.getLocationMessage(entry.message)); 209 buffer.write(entry.span.getLocationMessage(entry.message));
185 } else { 210 } else {
186 buffer.write(entry.message); 211 buffer.write(entry.message);
187 } 212 }
188 213
189 print(buffer); 214 print(buffer);
190 } 215 }
191 } 216 }
192 217
193 /// Listens to and handles the build results from [cascade]. 218 /// If [this] is done processing, schedule a [BuildResult] to be emitted on
194 void _handleResults(AssetCascade cascade) { 219 /// [results].
195 cascade.results.listen((result) { 220 ///
196 _cascadeResults[cascade.package] = result; 221 /// This schedules the result (as opposed to just emitting one directly on
197 // If any cascade hasn't yet finished, the overall build isn't finished 222 /// [BuildResult]) to ensure that calling multiple functions synchronously
198 // either. 223 /// produces only a single [BuildResult].
199 if (_cascadeResults.values.any((result) => result == null)) return; 224 void _tryScheduleResult() {
225 if (_isDirty) return;
226 if (_resultScheduled) return;
200 227
201 // Include all build errors for all cascades. If no cascades have 228 _resultScheduled = true;
202 // errors, the result will automatically be considered a success. 229 newFuture(() {
203 _resultsController.add(new BuildResult.aggregate(_cascadeResults.values)); 230 _resultScheduled = false;
231 if (_isDirty) return;
232
233 _lastResult = new BuildResult(_accumulatedErrors);
234 _accumulatedErrors.clear();
235 _resultsController.add(_lastResult);
204 }); 236 });
205 } 237 }
206 238
207 /// Run [body] in an error-handling [Zone] and pipe any unexpected errors to 239 /// Run [body] in an error-handling [Zone] and pipe any unexpected errors to
208 /// the error channel of [results]. 240 /// the error channel of [results].
209 /// 241 ///
210 /// [body] can return a value or a [Future] that will be piped to the returned 242 /// [body] can return a value or a [Future] that will be piped to the returned
211 /// [Future]. If it throws a [BarbackException], that exception will be piped 243 /// [Future]. If it throws a [BarbackException], that exception will be piped
212 /// to the returned [Future] as well. Any other exceptions will be piped to 244 /// to the returned [Future] as well. Any other exceptions will be piped to
213 /// [results]. 245 /// [results].
214 Future _inErrorZone(body()) { 246 Future _inErrorZone(body()) {
215 var completer = new Completer.sync(); 247 var completer = new Completer.sync();
216 runZoned(() { 248 runZoned(() {
217 syncFuture(body).then(completer.complete).catchError((error, stackTrace) { 249 syncFuture(body).then(completer.complete).catchError((error, stackTrace) {
218 if (error is! BarbackException) throw error; 250 if (error is! BarbackException) throw error;
219 completer.completeError(error, stackTrace); 251 completer.completeError(error, stackTrace);
220 }); 252 });
221 }, onError: (error, stackTrace) { 253 }, onError: (error, stackTrace) {
222 _lastUnexpectedError = error; 254 _lastUnexpectedError = error;
223 _lastUnexpectedErrorTrace = stackTrace; 255 _lastUnexpectedErrorTrace = stackTrace;
224 _resultsController.addError(error, stackTrace); 256 _resultsController.addError(error, stackTrace);
225 }); 257 });
226 return completer.future; 258 return completer.future;
227 } 259 }
228 } 260 }
OLDNEW
« no previous file with comments | « pkg/barback/lib/src/group_runner.dart ('k') | pkg/barback/lib/src/phase.dart » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698