Add: adding pipeline package not production ready

This commit is contained in:
Patrick Stewart 2024-10-03 07:58:46 -07:00
parent 4b112cd54b
commit 2d351c1319
9 changed files with 295 additions and 0 deletions

7
core/pipeline/.gitignore vendored Normal file
View file

@ -0,0 +1,7 @@
# https://dart.dev/guides/libraries/private-files
# Created by `dart pub`
.dart_tool/
# Avoid committing pubspec.lock for library packages; see
# https://dart.dev/guides/libraries/private-files#pubspeclock.
pubspec.lock

View file

@ -0,0 +1,3 @@
## 1.0.0
- Initial version.

10
core/pipeline/LICENSE.md Normal file
View file

@ -0,0 +1,10 @@
The MIT License (MIT)
The Laravel Framework is Copyright (c) Taylor Otwell
The Fabric Framework is Copyright (c) Vieo, Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

1
core/pipeline/README.md Normal file
View file

@ -0,0 +1 @@
<p align="center"><a href="https://protevus.com" target="_blank"><img src="https://git.protevus.com/protevus/branding/raw/branch/main/protevus-logo-bg.png"></a></p>

View file

@ -0,0 +1,30 @@
# This file configures the static analysis results for your project (errors,
# warnings, and lints).
#
# This enables the 'recommended' set of lints from `package:lints`.
# This set helps identify many issues that may lead to problems when running
# or consuming Dart code, and enforces writing Dart using a single, idiomatic
# style and format.
#
# If you want a smaller set of lints you can change this to specify
# 'package:lints/core.yaml'. These are just the most critical lints
# (the recommended set includes the core lints).
# The core lints are also what is used by pub.dev for scoring packages.
include: package:lints/recommended.yaml
# Uncomment the following section to specify additional rules.
# linter:
# rules:
# - camel_case_types
# analyzer:
# exclude:
# - path/to/excluded/files/**
# For more information about the core and recommended set of lints, see
# https://dart.dev/go/core-lints
# For additional information about configuring this file, see
# https://dart.dev/guides/language/analysis-options

View file

@ -0,0 +1,3 @@
library;
export 'src/pipeline.dart';

View file

@ -0,0 +1,223 @@
import 'dart:async';
import 'package:angel3_container/angel3_container.dart';
import 'package:logging/logging.dart';
/// Represents a series of "pipes" through which an object can be passed.
abstract class PipelineContract {
PipelineContract send(dynamic passable);
PipelineContract through(dynamic pipes);
PipelineContract pipe(dynamic pipes);
PipelineContract via(String method);
Future<dynamic> then(dynamic Function(dynamic) destination);
Future<dynamic> thenReturn();
}
/// Provides conditional execution methods for the pipeline.
mixin Conditionable<T> {
T when(bool Function() callback, void Function(T) callback2) {
if (callback()) {
callback2(this as T);
}
return this as T;
}
T unless(bool Function() callback, void Function(T) callback2) {
if (!callback()) {
callback2(this as T);
}
return this as T;
}
}
/// The primary class for building and executing pipelines.
class Pipeline with Conditionable<Pipeline> implements PipelineContract {
/// The container implementation.
Container? _container;
/// The object being passed through the pipeline.
dynamic _passable;
/// The array of class pipes.
final List<dynamic> _pipes = [];
/// The method to call on each pipe.
String _method = 'handle';
/// Logger for the pipeline.
final Logger _logger = Logger('Pipeline');
/// Create a new class instance.
Pipeline([this._container]);
/// Set the object being sent through the pipeline.
@override
Pipeline send(dynamic passable) {
_passable = passable;
return this;
}
/// Set the array of pipes.
@override
Pipeline through(dynamic pipes) {
_pipes.clear();
_pipes.addAll(pipes is Iterable ? pipes.toList() : [pipes]);
return this;
}
/// Push additional pipes onto the pipeline.
@override
Pipeline pipe(dynamic pipes) {
_pipes.addAll(pipes is Iterable ? pipes.toList() : [pipes]);
return this;
}
/// Set the method to call on the pipes.
@override
Pipeline via(String method) {
_method = method;
return this;
}
/// Run the pipeline with a final destination callback.
@override
Future<dynamic> then(dynamic Function(dynamic) destination) async {
var pipeline = pipes().fold<Function>(
(passable) => prepareDestination(destination),
(Function next, pipe) => (passable) => carry(pipe, passable, next),
);
return pipeline(_passable);
}
/// Run the pipeline and return the result.
@override
Future<dynamic> thenReturn() async {
return then((passable) => passable);
}
/// Get the final piece of the Closure onion.
Function prepareDestination(Function destination) {
return (passable) async {
try {
var result = destination(passable);
return result is Future ? await result : result;
} catch (e) {
return handleException(passable, e);
}
};
}
/// Get a Closure that represents a slice of the application onion.
Future<dynamic> carry(dynamic pipe, dynamic passable, Function next) async {
try {
if (pipe is Function) {
var result = pipe(passable, next);
return result is Future ? await result : result;
}
List<String> parameters = [];
if (pipe is String) {
var parts = parsePipeString(pipe);
pipe = parts[0];
parameters = parts.sublist(1);
}
var instance = pipe is String ? getContainer().make(pipe as Type) : pipe;
if (instance == null) {
throw Exception('Unable to resolve pipe: $pipe');
}
var method = instance.call(_method);
if (method == null) {
throw Exception('Method $_method not found on instance: $instance');
}
var result = Function.apply(
method,
[passable, next, ...parameters],
);
result = result is Future ? await result : result;
return handleCarry(result);
} catch (e) {
return handleException(passable, e);
}
}
/// Parse full pipe string to get name and parameters.
List<String> parsePipeString(String pipe) {
var parts = pipe.split(':');
return [parts[0], if (parts.length > 1) ...parts[1].split(',')];
}
/// Get the array of configured pipes.
List<dynamic> pipes() {
return List.unmodifiable(_pipes);
}
/// Get the container instance.
Container getContainer() {
if (_container == null) {
throw Exception(
'A container instance has not been passed to the Pipeline.');
}
return _container!;
}
/// Set the container instance.
Pipeline setContainer(Container container) {
_container = container;
return this;
}
/// Handle the value returned from each pipe before passing it to the next.
dynamic handleCarry(dynamic carry) {
if (carry is Future) {
return carry.then((value) => value ?? _passable);
}
return carry ?? _passable;
}
/// Handle the given exception.
dynamic handleException(dynamic passable, Object e) {
_logger.severe('Exception occurred in pipeline', e);
if (e is Exception) {
// You can add custom exception handling logic here
// For example, you might want to return a default value or transform the exception
}
throw e;
}
}
/// Extension methods for the Pipeline class.
extension PipelineExtensions on Pipeline {
/// Add a logging pipe to the pipeline.
Pipeline addLoggingPipe() {
return pipe((passable, next) {
_logger.info('Pipe input: $passable');
var result = next(passable);
_logger.info('Pipe output: $result');
return result;
});
}
/// Add an asynchronous pipe to the pipeline.
Pipeline addAsyncPipe(Future<dynamic> Function(dynamic) asyncOperation) {
return pipe((passable, next) async {
var result = await asyncOperation(passable);
return next(result);
});
}
/// Add a validation pipe to the pipeline.
Pipeline addValidationPipe(bool Function(dynamic) validator,
{String? errorMessage}) {
return pipe((passable, next) {
if (!validator(passable)) {
throw Exception(errorMessage ?? 'Validation failed');
}
return next(passable);
});
}
}

View file

@ -0,0 +1,18 @@
name: angel3_pipeline
description: The Pipeline Package for the Protevus Platform
version: 0.0.1
homepage: https://protevus.com
documentation: https://docs.protevus.com
repository: https://github.com/protevus/platformo
environment:
sdk: ^3.4.2
# Add regular dependencies here.
dependencies:
angel3_container: ^8.0.0
logging: ^1.1.0
dev_dependencies:
lints: ^3.0.0
test: ^1.24.0

View file