Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Clean up unused interfaces and update dependencies #79

Open
wants to merge 10 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .prettierrc.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
const fs = require('fs');

module.exports = JSON.parse(fs.readFileSync(__dirname + '/node_modules/@balena/lint/config/.prettierrc', 'utf8'));
23 changes: 9 additions & 14 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,24 +1,21 @@
Contrato
========
# Contrato

> The official contracts implementation

[![Documentation](https://github.com/product-os/contrato/actions/workflows/docs.yml/badge.svg)](https://product-os.github.io/contrato/modules/contrato.html)
[![Documentation](https://github.com/product-os/contrato/actions/workflows/docs.yml/badge.svg)](https://balena-io.github.io/contrato/modules/contrato.html)

Tests
-----
## Tests

Run the `test` npm script:

```sh
npm test
```

Contribute
----------
## Contribute

- Issue Tracker: [github.com/product-os/contrato/issues](https://github.com/product-os/contrato/issues)
- Source Code: [github.com/product-os/contrato](https://github.com/product-os/contrato)
- Issue Tracker: [github.com/product-os/contrato/issues](https://github.com/balena-io/contrato/issues)
- Source Code: [github.com/product-os/contrato](https://github.com/balena-io/contrato)

Before submitting a PR, please make sure that you include tests, and that the
linter runs without any warning:
Expand All @@ -27,13 +24,11 @@ linter runs without any warning:
npm run lint
```

Support
-------
## Support

If you're having any problem, please [raise an
issue](https://github.com/product-os/contrato/issues/new) on GitHub.
issue](https://github.com/balena-io/contrato/issues/new) on GitHub.

License
-------
## License

The project is licensed under the Apache 2.0 license.
298 changes: 4 additions & 294 deletions lib/blueprint.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,24 +4,14 @@
* Proprietary and confidential.
*/

import clone from 'lodash/clone';
import concat from 'lodash/concat';
import fill from 'lodash/fill';
import filter from 'lodash/filter';
import flatMap from 'lodash/flatMap';
import flatten from 'lodash/flatten';
import forEach from 'lodash/forEach';
import includes from 'lodash/includes';
import isEmpty from 'lodash/isEmpty';
import isEqual from 'lodash/isEqual';
import reduce from 'lodash/reduce';
import uniqWith from 'lodash/uniqWith';
import { compare } from 'semver';

import Contract from './contract';
import { parse } from './cardinality';
import type { BlueprintLayout, BlueprintObject } from './types/types';
import { BLUEPRINT } from './types/types';
import type { BlueprintLayout, BlueprintObject } from './types';
import { BLUEPRINT } from './types';
import {
cartesianProductWith,
flatten as flattenIterator,
Expand Down Expand Up @@ -91,273 +81,6 @@ export default class Blueprint extends Contract {
);
}

/**
* @summary Reproduce the blueprint in a universe
* @function
* @name module:contrato.Blueprint#reproduce
* @public
*
* @description
* This method will generate a set of contexts that consist of
* every possible valid combination that matches the blueprint
* layout.
*
* @param {Object} contract - contract
* @returns {Object[]} valid contexts
*
* @example
* const contract = new Contract({ ... })
* contract.addChildren([ ... ])
*
* const blueprint = new Blueprint({
* 'hw.device-type': 1,
* 'arch.sw': 1
* })
*
* const contexts = blueprint.reproduce(contract)
*
* contexts.forEach((context) => {
* console.log(context.toJSON())
* })
*/
sequence(
contract: Contract,
options = {
allowRequirements: true,
},
): Contract[] {
const layout = this.metadata.layout;

const combinations = reduce(
layout.finite.selectors,
(accumulator, value) => {
let internalAccumulator = accumulator;
forEach(value, (option) => {
const combi = uniqWith(
contract.getChildrenCombinations(option),
(left: Contract[], right: Contract[]) => {
return isEqual(left[0].raw, right[0].raw);
},
);
internalAccumulator = internalAccumulator.concat([combi]);
});
return internalAccumulator;
},
[] as Contract[][][],
);

forEach(combinations, (dimension) => {
dimension.sort((left, right) => {
return compare(left[0].raw.version, right[0].raw.version);
});
});

const currentPointer = new Array<number>(combinations.length);
fill(currentPointer, 0);

const bestPointer = new Array<number>(combinations.length);
for (let idx = 0; idx < combinations.length; idx++) {
bestPointer[idx] = combinations[idx].length - 1;
}

const buildContextFromPointer = (pointer: number[]) => {
const context = new Contract(this.raw.skeleton, {
hash: false,
});
const combination = [] as Contract[][];
for (let idx = 0; idx < combinations.length; idx++) {
combination.push(combinations[idx][pointer[idx]]);
}
context.addChildren(flatten(combination), {
rehash: true,
});

const references = context.getChildrenCrossReferencedContracts({
from: contract,
types: layout.infinite.types,
});

const contracts =
references.length === 0
? contract.getChildren({
types: layout.infinite.types,
})
: references;

context.addChildren(contracts, {
rehash: false,
});

for (const reference of contracts) {
if (
!context.satisfiesChildContract(reference, {
types: layout.types,
})
) {
context.removeChild(reference, {
rehash: false,
});
}
}

context.interpolate();

const requirements = context.getAllNotSatisfiedChildRequirements();
const newRequirements = uniqWith(
filter(concat(context.raw.requires, requirements)),
isEqual,
);
if (newRequirements && !isEmpty(newRequirements)) {
if (!options.allowRequirements) {
return null;
}
context.raw.requires = newRequirements;
context.interpolate();
}

const childCapabilities = filter(
uniqWith(
flatMap(context.getChildren(), (v: any) => v.raw.capabilities),
isEqual,
),
);

if (childCapabilities && !isEmpty(childCapabilities)) {
context.raw.capabilities = childCapabilities;
context.interpolate();
}

return context;
};
/**
* This will validate if a certain set of possibilities is good
*/
const checkSolutions = (pointer: number[]) => {
const context = buildContextFromPointer(pointer);
return !context
? false
: context.areChildrenSatisfied({
types: layout.types,
});
};

const checked: number[][] = [];

const pointerValue = (pointer: number[]) =>
reduce(pointer, (sum, value) => sum + value, 0);

let currentBestPointer = new Array<number>(combinations.length);
fill(currentBestPointer, 0);
const currentBestPointerValue = pointerValue(currentBestPointer);
let currentBestPath = [] as number[][];

const isValidPointer = (pointer: number[]) => {
if (includes(checked, pointer)) {
return false;
}
for (let idx = 0; idx < combinations.length; idx++) {
if (pointer[idx] > bestPointer[idx]) {
return false;
}
}
if (!checkSolutions(pointer)) {
return false;
}
return true;
};
/**
* Implements a simple recursive depth first search on the graph
* @param {*} combos asd asd
* @param {*} pointer asdas
*/
const search = (
combos: Contract[][][],
pointer: number[],
path: number[][],
) => {
checked.push(pointer);
for (let idx = 0; idx < combos.length; idx++) {
const possiblePointer = clone(pointer);
possiblePointer[idx] += 1;
if (isValidPointer(possiblePointer)) {
const currentPath = clone(path);
currentPath.push(possiblePointer);
if (isEqual(possiblePointer, bestPointer)) {
currentBestPath = currentPath;
return true;
}
const solutionValue = pointerValue(possiblePointer);
if (solutionValue > currentBestPointerValue) {
currentBestPointer = possiblePointer;
currentBestPath = currentPath;
}
if (search(combos, possiblePointer, currentPath)) {
return true;
}
return false;
}
}
return false;
};

if (isValidPointer(currentPointer)) {
currentBestPointer = currentPointer;
currentBestPath = [currentPointer];
search(combinations, currentPointer, [currentPointer]);
}

return reduce(
currentBestPath,
(seq, pointer) => {
const context = buildContextFromPointer(pointer);
if (context) {
if (
!context.areChildrenSatisfied({
types: layout.infinite.types,
})
) {
return seq;
}

context.interpolate();
seq.push(context);
}
return seq;
},
[] as Contract[],
);
}

/**
* @summary Reproduce the blueprint in a universe
* @function
* @name module:contrato.Blueprint#reproduce
* @public
*
* @description
* This method will generate a set of contexts that consist of
* every possible valid combination that matches the blueprint
* layout.
*
* @param {Object} contract - contract
* @returns {Object[]} valid contexts
*
* @example
* const contract = new Contract({ ... })
* contract.addChildren([ ... ])
*
* const blueprint = new Blueprint({
* 'hw.device-type': 1,
* 'arch.sw': 1
* })
*
* const contexts = blueprint.reproduceAsIterable(contract)
* contexts.forEach((context) => {
* console.log(context.toJSON());
* })
*/
reproduce(contract: Contract, asIterable?: false): Contract[];

/**
* @summary Reproduce the blueprint in a universe and return as an iterable
* @function
Expand All @@ -373,7 +96,6 @@ export default class Blueprint extends Contract {
* universe of contracts.
*
* @param {Object} contract - contract
* @param {boolean} asIterable - flag to indicate that the result should be an iterable
* @returns {Iterable<Object>} - an iterable over the valid contexts
*
* @example
Expand All @@ -385,24 +107,12 @@ export default class Blueprint extends Contract {
* 'arch.sw': 1
* })
*
* const contexts = blueprint.reproduceAsIterable(contract)
* const contexts = blueprint.reproduce(contract)
* for (const context of contexts) {
* console.log(context.toJSON());
* }
*/
reproduce(contract: Contract, asIterable: true): IterableIterator<Contract>;
reproduce(
contract: Contract,
asIterable?: boolean,
): IterableIterator<Contract> | Contract[];
reproduce(
contract: Contract,
asIterable = false,
): IterableIterator<Contract> | Contract[] {
if (!asIterable) {
return [...this.reproduce(contract, true)];
}

reproduce(contract: Contract): IterableIterator<Contract> {
const layout = this.metadata.layout;
const combinations = reduce(
layout.finite.selectors,
Expand Down
2 changes: 1 addition & 1 deletion lib/cardinality.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ import trim from 'lodash/trim';
* @type {Number}
* @constant
*/
const ORDERED_LIST_LENGTH: number = 2;
const ORDERED_LIST_LENGTH = 2;

/**
* @summary Parse a contracts cardinality tuple/string/number
Expand Down
Loading
Loading