Commit 845922ef authored by nanahira's avatar nanahira

first

parent 084047bb
Pipeline #8998 passed with stages
in 1 minute and 18 seconds
# compiled output
/dist
/node_modules
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
lerna-debug.log*
# OS
.DS_Store
# Tests
/coverage
/.nyc_output
# IDEs and editors
/.idea
.project
.classpath
.c9/
*.launch
.settings/
*.sublime-workspace
# IDE - VSCode
.vscode/*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json
/data
/output
/config.yaml
.git*
Dockerfile
.dockerignore
/tests
webpack.config.js
dist/*
build/*
*.js
module.exports = {
parser: '@typescript-eslint/parser',
parserOptions: {
project: 'tsconfig.json',
sourceType: 'module',
},
plugins: ['@typescript-eslint/eslint-plugin'],
extends: [
'plugin:@typescript-eslint/recommended',
'plugin:prettier/recommended',
],
root: true,
env: {
node: true,
jest: true,
},
ignorePatterns: ['.eslintrc.js'],
rules: {
'@typescript-eslint/interface-name-prefix': 'off',
'@typescript-eslint/explicit-function-return-type': 'off',
'@typescript-eslint/explicit-module-boundary-types': 'off',
'@typescript-eslint/no-explicit-any': 'off',
},
};
# compiled output
/dist
/node_modules
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
lerna-debug.log*
# OS
.DS_Store
# Tests
/coverage
/.nyc_output
# IDEs and editors
/.idea
.project
.classpath
.c9/
*.launch
.settings/
*.sublime-workspace
# IDE - VSCode
.vscode/*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json
/data
/output
/config.yaml
stages:
- build
- combine
- deploy
variables:
GIT_DEPTH: "1"
CONTAINER_TEST_IMAGE: $CI_REGISTRY_IMAGE:$CI_COMMIT_REF_SLUG
CONTAINER_TEST_ARM_IMAGE: $CI_REGISTRY_IMAGE:$CI_COMMIT_REF_SLUG-arm
CONTAINER_TEST_X86_IMAGE: $CI_REGISTRY_IMAGE:$CI_COMMIT_REF_SLUG-x86
CONTAINER_RELEASE_IMAGE: $CI_REGISTRY_IMAGE:latest
before_script:
- docker login -u $CI_REGISTRY_USER -p $CI_REGISTRY_PASSWORD $CI_REGISTRY
build-x86:
stage: build
tags:
- docker
script:
- TARGET_IMAGE=$CONTAINER_TEST_X86_IMAGE
- docker build --pull -t $TARGET_IMAGE .
- docker push $TARGET_IMAGE
build-arm:
stage: build
tags:
- docker-arm
script:
- TARGET_IMAGE=$CONTAINER_TEST_ARM_IMAGE
- docker build --pull -t $TARGET_IMAGE .
- docker push $TARGET_IMAGE
combine:
stage: combine
tags:
- docker
script:
- TARGET_IMAGE=$CONTAINER_TEST_IMAGE
- SOURCE_IMAGE_2=$CONTAINER_TEST_ARM_IMAGE
- SOURCE_IMAGE_1=$CONTAINER_TEST_X86_IMAGE
- docker pull $SOURCE_IMAGE_1
- docker pull $SOURCE_IMAGE_2
- docker manifest create $TARGET_IMAGE --amend $SOURCE_IMAGE_1 --amend
$SOURCE_IMAGE_2
- docker manifest push $TARGET_IMAGE
deploy_latest:
stage: deploy
tags:
- docker
script:
- TARGET_IMAGE=$CONTAINER_RELEASE_IMAGE
- SOURCE_IMAGE=$CONTAINER_TEST_IMAGE
- docker pull $SOURCE_IMAGE
- docker tag $SOURCE_IMAGE $TARGET_IMAGE
- docker push $TARGET_IMAGE
only:
- master
deploy_tag:
stage: deploy
tags:
- docker
script:
- TARGET_IMAGE=$CI_REGISTRY_IMAGE:$CI_COMMIT_TAG
- SOURCE_IMAGE=$CONTAINER_TEST_IMAGE
- docker pull $SOURCE_IMAGE
- docker tag $SOURCE_IMAGE $TARGET_IMAGE
- docker push $TARGET_IMAGE
only:
- tags
stages:
- install
- build
- deploy
variables:
GIT_DEPTH: "1"
npm_ci:
stage: install
tags:
- linux
script:
- npm ci
artifacts:
paths:
- node_modules
.build_base:
stage: build
tags:
- linux
dependencies:
- npm_ci
build:
extends:
- .build_base
script:
- npm run build
artifacts:
paths:
- dist/
unit-test:
extends:
- .build_base
script:
- npm run test
deploy_npm:
stage: deploy
dependencies:
- build
tags:
- linux
script:
- apt update;apt -y install coreutils
- echo $NPMRC | base64 --decode > ~/.npmrc
- npm publish . || true
only:
- master
/install-npm.sh
.git*
/data
/output
/config.yaml
.idea
.dockerignore
Dockerfile
/src
/coverage
/tests
/dist/tests
{
"singleQuote": true,
"trailingComma": "all"
}
\ No newline at end of file
FROM node:bullseye-slim as base
LABEL Author="Nanahira <nanahira@momobako.com>"
RUN apt update && apt -y install python3 build-essential && rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/*
WORKDIR /usr/src/app
COPY ./package*.json ./
FROM base as builder
RUN npm ci && npm cache clean --force
COPY . ./
RUN npm run build
FROM base
ENV NODE_ENV production
RUN npm ci && npm cache clean --force
COPY --from=builder /usr/src/app/dist ./dist
CMD [ "npm", "start" ]
The MIT License (MIT)
Copyright (c) 2021 Nanahira
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.
# ip-pcc
Utils for IP PCC in mcnetwork.
\ No newline at end of file
Utils for IP PCC in MCNetwork.
## API
* `getRules(weights: number[]): string[]` Get IP PCC rules in CIDR format, with given weights.
* `weights`: Array of weights.
export { getRules } from './src/index';
#!/bin/bash
npm install --save-dev \
@types/node \
typescript \
'@typescript-eslint/eslint-plugin@^4.28.2' \
'@typescript-eslint/parser@^4.28.2 '\
'eslint@^7.30.0' \
'eslint-config-prettier@^8.3.0' \
'eslint-plugin-prettier@^3.4.0' \
prettier \
jest \
@types/jest \
ts-jest \
rimraf
mkdir tests || true
This diff is collapsed.
{
"name": "ip-pcc",
"description": "Utils for IP PCC in MCNetwork.",
"version": "1.0.0",
"main": "dist/index.js",
"types": "dist/index.d.ts",
"scripts": {
"lint": "eslint --fix .",
"build": "rimraf dist && tsc",
"test": "jest --passWithNoTests",
"start": "node dist/index.js"
},
"repository": {
"type": "git",
"url": "https://code.mycard.moe/3rdeye/ip-pcc.git"
},
"author": "Nanahira <nanahira@momobako.com>",
"license": "MIT",
"keywords": [],
"bugs": {
"url": "https://code.mycard.moe/3rdeye/ip-pcc/issues"
},
"homepage": "https://code.mycard.moe/3rdeye/ip-pcc",
"jest": {
"moduleFileExtensions": [
"js",
"json",
"ts"
],
"rootDir": "tests",
"testRegex": ".*\\.spec\\.ts$",
"transform": {
"^.+\\.(t|j)s$": "ts-jest"
},
"collectCoverageFrom": [
"**/*.(t|j)s"
],
"coverageDirectory": "../coverage",
"testEnvironment": "node"
},
"devDependencies": {
"@types/ip": "^1.1.0",
"@types/jest": "^27.4.0",
"@types/lodash": "^4.14.178",
"@types/node": "^17.0.12",
"@typescript-eslint/eslint-plugin": "^4.33.0",
"@typescript-eslint/parser": "^4.33.0",
"eslint": "^7.32.0",
"eslint-config-prettier": "^8.3.0",
"eslint-plugin-prettier": "^3.4.1",
"jest": "^27.4.7",
"prettier": "^2.5.1",
"rimraf": "^3.0.2",
"ts-jest": "^27.1.3",
"typescript": "^4.5.5"
},
"dependencies": {
"ip": "^1.1.5",
"lodash": "^4.17.21"
}
}
import { getRules } from './index';
function run(...weight: number[]) {
console.log(`Result of ${weight.join(', ')}:`);
console.log(getRules(weight));
}
run(1, 1);
run(1, 2);
run(1, 1, 1);
run(1, 1, 1, 1);
run(1, 2, 3, 4, 5);
run(30, 30, 100);
import { fromLong } from 'ip';
import _ from 'lodash';
import { createHash } from 'crypto';
function gcd(a: number, b: number) {
if (b === 0) {
return a;
}
return gcd(b, a % b);
}
function gcds(n: number[]) {
return n.reduce((a, b) => gcd(a, b));
}
function formatIp(value: number, mask: number) {
return `${fromLong(value)}/${fromLong(mask)}`;
}
export interface Rule {
//srcValue: number;
//dstValue: number;
src: string;
dst: string;
}
function compactWeights(weights: number[]) {
const gcd = gcds(weights);
return weights.map((w) => w / gcd);
}
function rulesOfMaskLength(length: number) {
const srcMask = 0x1;
const dstMask = (0x1 << length) - 1;
const ruleCount = Math.pow(2, length + 1);
const rules: Rule[] = [];
for (let i = 0; i < ruleCount; i++) {
const srcValue = i & 0x1;
const dstValue = (i >> 1) & dstMask;
rules.push({
//srcValue,
//dstValue,
src: formatIp(srcValue, srcMask),
dst: formatIp(dstValue, dstMask),
});
}
return rules;
}
interface Slot {
rules: Rule[];
total: number;
remaining: number;
}
function selectSlot(rule: Rule, slots: Slot[]) {
return _.minBy(
slots.filter((s) =>
slots.every(
(other) =>
s.rules.filter((r) => r.dst === rule.dst).length <=
other.rules.filter((r) => r.dst === rule.dst).length,
),
),
(s) => s.rules.filter((r) => r.src === rule.src).length,
);
}
export function getRules(_weights: number[]) {
const weights = compactWeights(_weights);
const maskLength = Math.ceil(Math.log2(_.sum(weights)));
const rules = rulesOfMaskLength(maskLength);
const slots: Slot[] = weights.map((v) => ({
rules: [] as Rule[],
total: v,
remaining: v,
}));
let availableSlots = [...slots];
for (const rule of rules) {
const currentSlot = selectSlot(rule, availableSlots);
currentSlot.rules.push(rule);
--currentSlot.remaining;
if (currentSlot.remaining === 0) {
availableSlots = availableSlots.filter((s) => s !== currentSlot);
if (!availableSlots.length) {
availableSlots = [...slots];
availableSlots.forEach((s) => (s.remaining = s.total));
}
}
}
return slots.map((s) => s.rules);
}
import { getRules } from '../src';
describe('IP PCC', () => {
it('should work in basic form', () => {
const result = getRules([1, 1]);
expect(result.length).toBe(2);
expect(result.every((gatewayRule) => gatewayRule.length === 2)).toBe(true);
expect(
result.every(
(gatewayRule) =>
gatewayRule.filter((rule) => rule.src === '0.0.0.0/0.0.0.1')
.length === 1,
),
).toBe(true);
});
it('Should factorize result', () => {
expect(getRules([1, 1, 1, 1])).toEqual(getRules([2, 2, 2, 2]));
});
});
{
"compilerOptions": {
"outDir": "dist",
"module": "commonjs",
"target": "es2021",
"esModuleInterop": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"declaration": true,
"sourceMap": true
},
"compileOnSave": true,
"allowJs": true,
"include": [
"*.ts",
"src/**/*.ts",
"test/**/*.ts",
"tests/**/*.ts"
]
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment