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

feat: 支持灰度静默升级 #437

Open
wants to merge 1 commit 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
76 changes: 76 additions & 0 deletions packages/feflow-cli/src/core/resident/grey-update.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
import axios from 'axios';
import { getUserName } from '@feflow/report';
import { getLatestPackageJson } from '../../shared/package-json';

/** 灰度配置 */
export interface GreyConfig {
/** 灰度比例 */
ratio?: number;
/** 随时间增加的灰度比例 */
ratioList?: {
/** 灰度时间 */
day: number;
/** 灰度比例 */
ratio: number;
}[];
/** 灰度白名单 */
whitelist?: string[];
}

export const generatorGreyNum = (name: string, version: string) => {
const userName = getUserName();
const str = `${name}${version}${userName}`;
let result = 0;

for (let i = 0; i < str.length; i++) {
result += str.charCodeAt(i);
}

return result % 100;
};

export const getDayDiff = (date: string) => Math.ceil(((+new Date()) - (+new Date(date))) / (1000 * 60 * 60 * 24));

export const getGreyConfig = async (name: string) => {
const response = await axios.get('https://gui.woa.com/apply/grey-config', { proxy: false, data: { name } });
const { data } = response.data;
const { grey_config } = data;

if (grey_config) {
const greyConfig = JSON.parse(grey_config);

if (greyConfig.ratio || greyConfig.ratio_list[0]?.ratio) {
return greyConfig;
}
}
};

export const getGreyVersion = async (name: string, packageManager: string) => {
const { packageJson, time } = await getLatestPackageJson(name, packageManager);
const serverGreyConfig = await getGreyConfig(name);
const greyConfig: GreyConfig = serverGreyConfig || packageJson?.greyConfig;

if (!greyConfig) return packageJson.version;

const userName = getUserName();
const { ratio, ratioList, whitelist = [] } = greyConfig;

if (whitelist.includes(userName)) return packageJson.version;

let selectedRatio = ratio || 0;

if (ratioList) {
const currentDay = getDayDiff(time);
ratioList.forEach((item) => {
if (item.day <= currentDay) {
selectedRatio = item.ratio;
}
});
}

const greyNum = generatorGreyNum(name, packageJson.version);

if (selectedRatio >= greyNum) return packageJson.version;

return '';
};
16 changes: 4 additions & 12 deletions packages/feflow-cli/src/core/resident/update-beat.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,9 @@ import fs from 'fs';
import path from 'path';
import semver from 'semver';
import osenv from 'osenv';
import spawn from 'cross-spawn';
import _ from 'lodash';
import { UpdateData, UniversalPluginUpdateMsg } from './';
import LockFile from '../../shared/lock-file';
import packageJson from '../../shared/package-json';
import { parseYaml } from '../../shared/yaml';
import { setServerUrl } from '../../shared/git';
import { UniversalPkg } from '../universal-pkg/dep/pkg';
Expand All @@ -26,12 +24,13 @@ import {
HEART_BEAT_PID,
} from '../../shared/constant';
import createLogger from '../logger';
import { getInstalledPlugins, getLatestVersion, getUniversalPluginVersion } from './utils';
import { getInstalledPlugins, getUniversalPluginVersion } from './utils';
import { getPkgInfo } from '../native/install';
import Feflow from '../index';
import { isValidConfig } from '../../shared/type-predicates';
import { fileExit, writeFileSync } from '../../shared/file';
import pkgJson from '../../../package.json';
import { getGreyVersion } from './grey-update';

interface ErrorInstance {
name: string;
Expand Down Expand Up @@ -84,7 +83,7 @@ const queryCliUpdate = async () => {
return;
}

const latestVersion = await getLatestVersion('@feflow/cli', config.packageManager);
const latestVersion = await getGreyVersion('@feflow/cli', config.packageManager);
if (latestVersion && semver.gt(latestVersion, pkgJson.version)) {
const updateData = (await updateFile.read(UPDATE_KEY)) as UpdateData;
if (updateData?.latest_cli_version !== latestVersion) {
Expand All @@ -110,14 +109,7 @@ const queryPluginsUpdate = async () => {
});
const pkgJson = JSON.parse(pkgJsonStr);
const localVersion = pkgJson.version;
const registryUrl = spawn
.sync(config.packageManager, ['config', 'get', 'registry'], {
windowsHide: true,
})
.stdout.toString()
.replace(/\n/, '')
.replace(/\/$/, '');
const latestVersion = await packageJson(name, registryUrl).catch((err) => {
const latestVersion = await getGreyVersion(name, config.packageManager).catch((err) => {
logger.debug('Check plugin update error', err);
});

Expand Down
41 changes: 25 additions & 16 deletions packages/feflow-cli/src/shared/package-json.ts
Original file line number Diff line number Diff line change
@@ -1,23 +1,32 @@
import axios, { AxiosResponse } from 'axios';
import axios from 'axios';
import semver from 'semver';
import { getNpmRegistryUrl } from '../core/resident/utils';

export default function packageJson(name: string, registry: string): Promise<string> {
export const getPackageInfo = async (name: string, registry: string) => {
const names = (name || '').split('@');
const version = !names[0] ? names[2] : names[1];
const isValidVersion = semver.valid(version) || version === 'latest';
const url = `${registry}/${isValidVersion ? `@${names[1]}/${names[2]}` : name}`;
return axios
.get(url, {
proxy: false,
})
.then((response: AxiosResponse) => {
const { data } = response || { 'dist-tags': {} };
if (!isValidVersion) {
const version = data['dist-tags'].latest;
return version || '';
}
// 指定包的版本情况
return data.version || '';
})
.catch((err: object) => err);
const response = await axios.get(url, { proxy: false });
const { data } = response;

return { data, isValidVersion };
};

export const getLatestPackageJson = async (name: string, packageManager: string) => {
const registryUrl = getNpmRegistryUrl(packageManager);
const { data } = await getPackageInfo(name, registryUrl);
const latestVersion = data['dist-tags'].latest;

return { packageJson: data.versions[latestVersion], time: data.time[latestVersion] };
};

export default async function packageJson(name: string, registry: string) {
const { data, isValidVersion } = await getPackageInfo(name, registry);
if (!isValidVersion) {
const version = data['dist-tags'].latest;
return version || '';
}
// 指定包的版本情况
return data.version || '';
}
3 changes: 2 additions & 1 deletion packages/feflow-report/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import path from 'path';
import { spawn } from 'child_process';
import type Feflow from '@feflow/cli';
import { HOOK_TYPE_BEFORE, HOOK_TYPE_AFTER, REPORT_JSON, REPORT_COMMAND_ERR } from './constants';
import { getProject, getKeyFormFile, setKeyToFile } from './common/utils';
import { getProject, getKeyFormFile, setKeyToFile, getUserName } from './common/utils';

const reportProcess = path.join(__dirname, './report');

Expand Down Expand Up @@ -144,4 +144,5 @@ class Report {
};
}

export { getUserName };
export default Report;
Loading