mirror of
https://github.com/whyour/qinglong.git
synced 2026-11-17 15:51:07 +08:00
Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8976447b1e | ||
|
|
15d54866a8 |
@@ -33,10 +33,6 @@ on:
|
||||
type: choice
|
||||
options: [branch, tag]
|
||||
default: branch
|
||||
npm_rc_version:
|
||||
description: Publish the verified main npm RC from develop, for example 2.25.0-rc.0
|
||||
type: string
|
||||
default: ''
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
@@ -251,7 +247,7 @@ jobs:
|
||||
version: "8.3.1"
|
||||
- uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version: "24"
|
||||
node-version: "20"
|
||||
cache: "pnpm"
|
||||
cache-dependency-path: pnpm-lock.yaml
|
||||
|
||||
@@ -340,7 +336,7 @@ jobs:
|
||||
version: "8.3.1"
|
||||
- uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version: "24"
|
||||
node-version: "20"
|
||||
cache: "pnpm"
|
||||
cache-dependency-path: pnpm-lock.yaml
|
||||
|
||||
@@ -398,7 +394,7 @@ jobs:
|
||||
SOURCE_COMMIT=${{ github.sha }}
|
||||
network: host
|
||||
# Keep s390x on Debian: npm can hang under QEMU with Alpine (nodejs/docker-node#1973).
|
||||
platforms: linux/amd64,linux/arm64,linux/ppc64le,linux/s390x
|
||||
platforms: linux/amd64,linux/arm/v7,linux/arm64,linux/ppc64le,linux/s390x
|
||||
context: .
|
||||
file: ./docker/Dockerfile.debian
|
||||
push: true
|
||||
@@ -409,10 +405,159 @@ jobs:
|
||||
cache-from: type=registry,ref=whyour/qinglong:cache-debian
|
||||
cache-to: type=registry,ref=whyour/qinglong:cache-debian,mode=max
|
||||
|
||||
# One unmodified amd64 package for migration acceptance only. This does not
|
||||
build-alpine310:
|
||||
if: ${{ github.ref_name == 'master' }}
|
||||
needs: build-static
|
||||
runs-on: ubuntu-22.04
|
||||
permissions:
|
||||
packages: write
|
||||
contents: read
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
- uses: actions/download-artifact@v7
|
||||
with:
|
||||
name: qinglong-static-${{ github.sha }}
|
||||
path: static/
|
||||
- uses: pnpm/action-setup@v6
|
||||
with:
|
||||
version: "8.3.1"
|
||||
- uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version: "20"
|
||||
cache: "pnpm"
|
||||
cache-dependency-path: pnpm-lock.yaml
|
||||
|
||||
- name: Read version from version.yaml
|
||||
id: version
|
||||
run: |
|
||||
VERSION=$(grep '^version:' version.yaml | awk '{print $2}')
|
||||
echo "version=$VERSION" >> $GITHUB_OUTPUT
|
||||
|
||||
- name: Setup timezone
|
||||
run: sudo timedatectl set-timezone Asia/Shanghai
|
||||
|
||||
- name: Login to DockerHub
|
||||
uses: docker/login-action@v4
|
||||
with:
|
||||
username: ${{ secrets.DOCKER_USERNAME }}
|
||||
password: ${{ secrets.DOCKER_PASSWORD }}
|
||||
|
||||
- name: Login to GHCR
|
||||
uses: docker/login-action@v4
|
||||
with:
|
||||
registry: ghcr.io
|
||||
username: ${{ github.repository_owner }}
|
||||
password: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
- name: Set up QEMU
|
||||
uses: docker/setup-qemu-action@v4
|
||||
with:
|
||||
cache-image: false
|
||||
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@v4
|
||||
|
||||
- name: Build and push (Alpine Python 3.10)
|
||||
uses: docker/build-push-action@v7
|
||||
with:
|
||||
build-args: |
|
||||
QL_MAINTAINER=${{ github.repository_owner }}
|
||||
QL_BRANCH=${{ github.ref_name }}
|
||||
SOURCE_COMMIT=${{ github.sha }}
|
||||
network: host
|
||||
platforms: linux/amd64,linux/arm/v6,linux/arm/v7,linux/arm64,linux/ppc64le,linux/s390x,linux/386
|
||||
context: .
|
||||
file: ./docker/Dockerfile.310
|
||||
push: true
|
||||
provenance: mode=max
|
||||
sbom: true
|
||||
tags: |
|
||||
whyour/qinglong:python3.10
|
||||
whyour/qinglong:${{ steps.version.outputs.version }}-python3.10
|
||||
cache-from: type=registry,ref=whyour/qinglong:cache-alpine-python3.10
|
||||
cache-to: type=registry,ref=whyour/qinglong:cache-alpine-python3.10,mode=max
|
||||
|
||||
build-debian310:
|
||||
if: ${{ github.ref_name == 'master' }}
|
||||
needs: build-static
|
||||
runs-on: ubuntu-22.04
|
||||
permissions:
|
||||
packages: write
|
||||
contents: read
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
- uses: actions/download-artifact@v7
|
||||
with:
|
||||
name: qinglong-static-${{ github.sha }}
|
||||
path: static/
|
||||
- uses: pnpm/action-setup@v6
|
||||
with:
|
||||
version: "8.3.1"
|
||||
- uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version: "20"
|
||||
cache: "pnpm"
|
||||
cache-dependency-path: pnpm-lock.yaml
|
||||
|
||||
- name: Read version from version.yaml
|
||||
id: version
|
||||
run: |
|
||||
VERSION=$(grep '^version:' version.yaml | awk '{print $2}')
|
||||
echo "version=$VERSION" >> $GITHUB_OUTPUT
|
||||
|
||||
- name: Setup timezone
|
||||
run: sudo timedatectl set-timezone Asia/Shanghai
|
||||
|
||||
- name: Login to DockerHub
|
||||
uses: docker/login-action@v4
|
||||
with:
|
||||
username: ${{ secrets.DOCKER_USERNAME }}
|
||||
password: ${{ secrets.DOCKER_PASSWORD }}
|
||||
|
||||
- name: Login to GHCR
|
||||
uses: docker/login-action@v4
|
||||
with:
|
||||
registry: ghcr.io
|
||||
username: ${{ github.repository_owner }}
|
||||
password: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
- name: Set up QEMU
|
||||
uses: docker/setup-qemu-action@v4
|
||||
with:
|
||||
cache-image: false
|
||||
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@v4
|
||||
|
||||
- name: Build and push (Debian Python 3.10)
|
||||
uses: docker/build-push-action@v7
|
||||
with:
|
||||
build-args: |
|
||||
QL_MAINTAINER=${{ github.repository_owner }}
|
||||
QL_BRANCH=${{ github.ref_name }}
|
||||
SOURCE_COMMIT=${{ github.sha }}
|
||||
network: host
|
||||
# Keep s390x on Debian: npm can hang under QEMU with Alpine (nodejs/docker-node#1973).
|
||||
platforms: linux/amd64,linux/arm/v7,linux/arm64,linux/ppc64le,linux/s390x
|
||||
context: .
|
||||
file: ./docker/Dockerfile.debian310
|
||||
push: true
|
||||
provenance: mode=max
|
||||
sbom: true
|
||||
tags: |
|
||||
whyour/qinglong:debian-python3.10
|
||||
whyour/qinglong:${{ steps.version.outputs.version }}-debian-python3.10
|
||||
cache-from: type=registry,ref=whyour/qinglong:cache-debian-python3.10
|
||||
cache-to: type=registry,ref=whyour/qinglong:cache-debian-python3.10,mode=max
|
||||
|
||||
# Unmodified amd64 packages for glibc and musl migration acceptance. This does not
|
||||
# publish bundles or advance development/formal channel indexes.
|
||||
build-npm-migration-bundle:
|
||||
needs: build-debian
|
||||
needs: [build-debian, build-alpine]
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
libc: [glibc, musl]
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 20
|
||||
steps:
|
||||
@@ -420,7 +565,7 @@ jobs:
|
||||
- uses: docker/setup-buildx-action@v4
|
||||
- name: Export the official platform package from this run's image digest
|
||||
env:
|
||||
IMAGE_DIGEST: ${{ needs.build-debian.outputs.image-digest }}
|
||||
IMAGE_DIGEST: ${{ matrix.libc == 'musl' && needs.build-alpine.outputs.image-digest || needs.build-debian.outputs.image-digest }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
[[ "$IMAGE_DIGEST" =~ ^sha256:[a-f0-9]{64}$ ]]
|
||||
@@ -428,20 +573,21 @@ jobs:
|
||||
docker buildx build --platform linux/amd64 --build-arg "BASE_IMAGE=$image" --file docker/Dockerfile.upgrade-bundle --output "type=local,dest=$RUNNER_TEMP/npm-migration-bundle" .
|
||||
- uses: actions/upload-artifact@v6
|
||||
with:
|
||||
name: npm-migration-bundle-${{ github.sha }}
|
||||
name: npm-migration-bundle-${{ matrix.libc }}-${{ github.sha }}
|
||||
path: ${{ runner.temp }}/npm-migration-bundle/*
|
||||
if-no-files-found: error
|
||||
retention-days: 3
|
||||
|
||||
verify-npm-package:
|
||||
needs: [build-static, build-npm-migration-bundle]
|
||||
needs: [build-static, build-npm-migration-bundle, build-alpine]
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 30
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
node: ['20.18.1', '24']
|
||||
container: node:${{ matrix.node }}-bookworm
|
||||
node: ['20.18.1', '22.17.0', '24', 'alpine']
|
||||
container:
|
||||
image: ${{ matrix.node == 'alpine' && format('ghcr.io/{0}@{1}', github.repository, needs.build-alpine.outputs.image-digest) || format('node:{0}-bookworm', matrix.node) }}
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
- uses: actions/download-artifact@v6
|
||||
@@ -450,22 +596,30 @@ jobs:
|
||||
path: ${{ runner.temp }}/npm-panel/
|
||||
- uses: actions/download-artifact@v6
|
||||
with:
|
||||
name: npm-migration-bundle-${{ github.sha }}
|
||||
name: npm-migration-bundle-${{ matrix.node == 'alpine' && 'musl' || 'glibc' }}-${{ github.sha }}
|
||||
path: ${{ runner.temp }}/npm-migration-bundle/
|
||||
- name: Install isolated service test tools
|
||||
run: |
|
||||
if [ -f /etc/alpine-release ]; then
|
||||
apk add --no-cache python3 openssl curl jq nginx procps make g++
|
||||
else
|
||||
apt-get update
|
||||
apt-get install -y --no-install-recommends python3 openssl curl jq nginx procps
|
||||
fi
|
||||
# The published legacy launcher resets PATH to standard directories.
|
||||
# /usr/local is confined to this disposable job container; PM2_HOME
|
||||
# remains private to each verification run.
|
||||
npm install --global --prefix /usr/local --no-audit --no-fund pm2@6.0.14
|
||||
- name: Install and upgrade the exact npm archive
|
||||
if: matrix.node != '20.18.1'
|
||||
env:
|
||||
QL_PANEL_PACKAGE_TEST_ISOLATED: '1'
|
||||
QL_PANEL_TEST_PM2: /usr/local/bin/pm2
|
||||
QL_PANEL_TEST_BUNDLE_DIR: ${{ runner.temp }}/npm-migration-bundle
|
||||
run: node scripts/verify-panel-package.cjs verify "$RUNNER_TEMP/npm-panel" "$RUNNER_TEMP/npm-panel-results"
|
||||
- name: Reject an unsupported runtime while preserving the old installation
|
||||
if: matrix.node == '20.18.1'
|
||||
run: node scripts/verify-panel-runtime-floor.cjs "$RUNNER_TEMP/npm-panel" "$RUNNER_TEMP/npm-panel-results"
|
||||
- uses: actions/upload-artifact@v6
|
||||
with:
|
||||
name: qinglong-npm-verification-${{ matrix.node }}-${{ github.sha }}
|
||||
@@ -474,8 +628,8 @@ jobs:
|
||||
retention-days: 14
|
||||
|
||||
publish:
|
||||
if: ${{ github.repository == 'whyour/qinglong' && (github.ref == 'refs/heads/master' || (github.event_name == 'workflow_dispatch' && github.ref == 'refs/heads/develop')) }}
|
||||
needs: [build-alpine, build-debian, verify-npm-package]
|
||||
if: ${{ github.repository == 'whyour/qinglong' && github.ref == 'refs/heads/master' }}
|
||||
needs: [build-alpine, build-debian, build-alpine310, build-debian310, verify-npm-package]
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: read
|
||||
@@ -495,8 +649,6 @@ jobs:
|
||||
|
||||
- name: Publish npm package with OIDC
|
||||
shell: bash
|
||||
env:
|
||||
NPM_RC_VERSION: ${{ inputs.npm_rc_version }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
shopt -s nullglob
|
||||
@@ -509,21 +661,11 @@ jobs:
|
||||
metadata=$(tar -xOf "$archive" package/package.json)
|
||||
name=$(jq -er '.name | select(. == "@whyour/qinglong")' <<< "$metadata")
|
||||
version=$(jq -er '.version | select(type == "string")' <<< "$metadata")
|
||||
if [[ "${GITHUB_EVENT_NAME:-}" == workflow_dispatch && "${GITHUB_REF:-}" == refs/heads/develop ]]; then
|
||||
if [[ ! "${NPM_RC_VERSION:-}" =~ ^[0-9]+\.[0-9]+\.[0-9]+-rc\.[0-9]+$ || "$version" != "${NPM_RC_VERSION:-}" ]]; then
|
||||
echo '::error::Develop npm publication requires the exact requested RC archive version.'
|
||||
exit 1
|
||||
fi
|
||||
fi
|
||||
if npm view "$name@$version" version --json --registry=https://registry.npmjs.org > "$RUNNER_TEMP/npm-version.json" 2> "$RUNNER_TEMP/npm-version-error.log"; then
|
||||
jq -e --arg version "$version" '. == $version' "$RUNNER_TEMP/npm-version.json" > /dev/null
|
||||
echo "::notice::$name@$version is already published; skipping npm publication for this image rebuild."
|
||||
elif jq -e '.error.code == "E404"' "$RUNNER_TEMP/npm-version.json" > /dev/null; then
|
||||
if [[ "${GITHUB_EVENT_NAME:-}" == workflow_dispatch && "${GITHUB_REF:-}" == refs/heads/develop ]]; then
|
||||
npm publish "./$archive" --ignore-scripts --access public --tag rc --registry=https://registry.npmjs.org
|
||||
else
|
||||
npm publish "./$archive" --ignore-scripts --access public --registry=https://registry.npmjs.org
|
||||
fi
|
||||
npm publish "$archive" --ignore-scripts --access public --registry=https://registry.npmjs.org
|
||||
else
|
||||
echo '::error::Could not check the published npm version; refusing to publish.'
|
||||
exit 1
|
||||
@@ -533,8 +675,7 @@ jobs:
|
||||
# Both channels publish packages from this run's immutable image digests.
|
||||
if: ${{ !inputs.static_sync_only && (github.ref == 'refs/heads/master' || github.ref == 'refs/heads/develop') }}
|
||||
needs: [build-alpine, build-debian]
|
||||
# Node 24 can SIGILL while archiving ARM64 musl under x64 QEMU.
|
||||
runs-on: ${{ matrix.platform == 'linux/arm64' && 'ubuntu-24.04-arm' || 'ubuntu-22.04' }}
|
||||
runs-on: ubuntu-22.04
|
||||
timeout-minutes: 90
|
||||
permissions:
|
||||
contents: read
|
||||
@@ -551,13 +692,13 @@ jobs:
|
||||
- { platform: linux/s390x, libc: musl, name: s390x-musl }
|
||||
- { platform: linux/386, libc: musl, name: ia32-musl }
|
||||
- { platform: linux/amd64, libc: glibc, name: x64-glibc }
|
||||
- { platform: linux/arm/v7, libc: glibc, name: armv7-glibc }
|
||||
- { platform: linux/arm64, libc: glibc, name: arm64-glibc }
|
||||
- { platform: linux/ppc64le, libc: glibc, name: ppc64-glibc }
|
||||
- { platform: linux/s390x, libc: glibc, name: s390x-glibc }
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
- uses: docker/setup-qemu-action@v4
|
||||
if: ${{ matrix.platform != 'linux/arm64' }}
|
||||
with:
|
||||
cache-image: false
|
||||
- uses: docker/setup-buildx-action@v4
|
||||
|
||||
@@ -25,7 +25,7 @@ on:
|
||||
type: boolean
|
||||
default: false
|
||||
prerelease_version:
|
||||
description: Develop only, e.g. 0.1.5-beta.0 (alpha/beta/rc)
|
||||
description: Develop only, e.g. 0.1.2-beta.0 (alpha/beta/rc)
|
||||
type: string
|
||||
default: ''
|
||||
|
||||
@@ -93,26 +93,8 @@ jobs:
|
||||
if-no-files-found: error
|
||||
retention-days: 14
|
||||
|
||||
platform-smoke:
|
||||
runs-on: ${{ matrix.os }}
|
||||
timeout-minutes: 15
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
os: [windows-latest, ubuntu-24.04-arm]
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
- uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version: '24'
|
||||
cache: npm
|
||||
cache-dependency-path: cli/package-lock.json
|
||||
- run: npm ci --prefix cli --no-audit --no-fund
|
||||
- run: npm run build:cli
|
||||
- run: node --test cli/test/remote/platformSmoke.test.cjs
|
||||
|
||||
publish:
|
||||
needs: [package, platform-smoke]
|
||||
needs: package
|
||||
if: >-
|
||||
github.repository == 'whyour/qinglong' &&
|
||||
((github.ref == 'refs/heads/master' &&
|
||||
|
||||
@@ -6,11 +6,6 @@ on:
|
||||
- '.github/workflows/release-readiness.yml'
|
||||
- 'package.json'
|
||||
- 'pnpm-lock.yaml'
|
||||
- 'docker/Dockerfile*'
|
||||
- 'shell/node-runtime-probe.cjs'
|
||||
- 'scripts/verify-panel-package.cjs'
|
||||
- 'scripts/verify-image-node-layers.py'
|
||||
- 'test/back/node-runtime-probe.test.cjs'
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
@@ -36,7 +31,7 @@ jobs:
|
||||
version: '8.3.1'
|
||||
- uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version: '20'
|
||||
node-version: '22'
|
||||
cache: pnpm
|
||||
- run: pnpm install --frozen-lockfile
|
||||
- run: pnpm build:front && pnpm build:back && pnpm build:info
|
||||
@@ -46,13 +41,6 @@ jobs:
|
||||
path: static/
|
||||
include-hidden-files: true
|
||||
if-no-files-found: error
|
||||
- name: Pack the verified npm archive for isolated runtime validation
|
||||
run: node scripts/verify-panel-package.cjs pack "$RUNNER_TEMP/npm-panel"
|
||||
- uses: actions/upload-artifact@v6
|
||||
with:
|
||||
name: release-readiness-npm-panel
|
||||
path: ${{ runner.temp }}/npm-panel/
|
||||
if-no-files-found: error
|
||||
|
||||
images:
|
||||
needs: [regression, static]
|
||||
@@ -69,7 +57,15 @@ jobs:
|
||||
- image: debian
|
||||
file: docker/Dockerfile.debian
|
||||
cache: debian
|
||||
platforms: linux/amd64,linux/arm64,linux/ppc64le,linux/s390x
|
||||
platforms: linux/amd64,linux/arm/v7,linux/arm64,linux/ppc64le,linux/s390x
|
||||
- image: alpine-python3.10
|
||||
file: docker/Dockerfile.310
|
||||
cache: alpine-python3.10
|
||||
platforms: linux/amd64,linux/arm/v6,linux/arm/v7,linux/arm64,linux/ppc64le,linux/s390x,linux/386
|
||||
- image: debian-python3.10
|
||||
file: docker/Dockerfile.debian310
|
||||
cache: debian-python3.10
|
||||
platforms: linux/amd64,linux/arm/v7,linux/arm64,linux/ppc64le,linux/s390x
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
with:
|
||||
@@ -124,48 +120,17 @@ jobs:
|
||||
run: |
|
||||
docker run --rm --network none --entrypoint node \
|
||||
qinglong-readiness:${{ matrix.image }} \
|
||||
-e 'const assert=require("node:assert/strict"); const {createRequire}=require("node:module"); for(const [name,want] of Object.entries({"@grpc/grpc-js":"1.14.5",compression:"1.8.2",multer:"2.4.0",sequelize:"6.37.8"}))assert.equal(require(name+"/package.json").version,want); const expressRequire=createRequire(require.resolve("express")); assert.equal(expressRequire("proxy-addr/package.json").version,"2.0.8"); const sockRequire=createRequire(require.resolve("sockjs")); assert.equal(sockRequire("websocket-driver/package.json").version,"0.7.5"); require("sqlite3"); require("nodemailer"); require("undici"); console.log("Minimal production patches and runtime imports verified")'
|
||||
- name: Load ARMv6 image for SQLite and Node regression checks
|
||||
if: startsWith(matrix.image, 'alpine')
|
||||
uses: docker/build-push-action@v7
|
||||
with:
|
||||
context: .
|
||||
file: ${{ matrix.file }}
|
||||
platforms: linux/arm/v6
|
||||
build-args: |
|
||||
QL_URL=${{ steps.source.outputs.url }}
|
||||
QL_BRANCH=${{ steps.source.outputs.branch }}
|
||||
SOURCE_COMMIT=${{ steps.source.outputs.sha }}
|
||||
tags: qinglong-readiness:${{ matrix.image }}-armv6
|
||||
load: true
|
||||
push: false
|
||||
provenance: false
|
||||
sbom: false
|
||||
- name: Verify ARMv6 SQLite on an ARM1176 CPU without networking
|
||||
if: startsWith(matrix.image, 'alpine')
|
||||
-e 'const assert=require("node:assert/strict"); const {createRequire}=require("node:module"); for(const [name,want] of Object.entries({"@grpc/grpc-js":"1.14.5",compression:"1.8.2",multer:"2.4.0"}))assert.equal(require(name+"/package.json").version,want); const expressRequire=createRequire(require.resolve("express")); assert.equal(expressRequire("proxy-addr/package.json").version,"2.0.8"); const sockRequire=createRequire(require.resolve("sockjs")); assert.equal(sockRequire("websocket-driver/package.json").version,"0.7.5"); assert.equal(typeof require("@mikro-orm/sql").NodeSqliteDialect,"function"); const db=new (require("node:sqlite").DatabaseSync)(":memory:"); assert.equal(db.prepare("SELECT 42 AS value").get().value,42); db.close(); require("nodemailer"); require("undici"); console.log("Minimal production patches and runtime imports verified")'
|
||||
- name: Export native Debian image for isolated dev validation
|
||||
if: matrix.image == 'debian'
|
||||
run: |
|
||||
docker run --rm --network none --platform linux/arm/v6 \
|
||||
-e QEMU_CPU=arm1176 --entrypoint node \
|
||||
qinglong-readiness:${{ matrix.image }}-armv6 --jitless \
|
||||
-e 'const assert=require("node:assert/strict"); const sqlite3=require("sqlite3"); const db=new sqlite3.Database(":memory:"); db.get("SELECT 42 AS n",(error,row)=>{assert.ifError(error); assert.equal(row.n,42); db.close()});'
|
||||
- name: Check Node binaries in every serialized image layer
|
||||
if: startsWith(matrix.image, 'alpine')
|
||||
run: |
|
||||
docker save qinglong-readiness:${{ matrix.image }} -o "$RUNNER_TEMP/node-layers-amd64.tar"
|
||||
docker save qinglong-readiness:${{ matrix.image }}-armv6 -o "$RUNNER_TEMP/node-layers-arm.tar"
|
||||
python3 scripts/verify-image-node-layers.py "$RUNNER_TEMP/node-layers-amd64.tar" amd64
|
||||
python3 scripts/verify-image-node-layers.py "$RUNNER_TEMP/node-layers-arm.tar" arm
|
||||
rm "$RUNNER_TEMP/node-layers-amd64.tar" "$RUNNER_TEMP/node-layers-arm.tar"
|
||||
- name: Export native image for isolated dev validation
|
||||
if: matrix.image == 'debian' || matrix.image == 'alpine'
|
||||
run: |
|
||||
docker save qinglong-readiness:${{ matrix.image }} | gzip -1 > release-readiness-${{ matrix.image }}-image.tar.gz
|
||||
sha256sum release-readiness-${{ matrix.image }}-image.tar.gz > release-readiness-${{ matrix.image }}-image.sha256
|
||||
docker image inspect qinglong-readiness:${{ matrix.image }} > release-readiness-${{ matrix.image }}-image.json
|
||||
docker save qinglong-readiness:debian | gzip -1 > release-readiness-debian-image.tar.gz
|
||||
sha256sum release-readiness-debian-image.tar.gz > release-readiness-debian-image.sha256
|
||||
docker image inspect qinglong-readiness:debian > release-readiness-debian-image.json
|
||||
- uses: actions/upload-artifact@v6
|
||||
if: matrix.image == 'debian' || matrix.image == 'alpine'
|
||||
if: matrix.image == 'debian'
|
||||
with:
|
||||
name: release-readiness-${{ matrix.image }}-image
|
||||
path: release-readiness-${{ matrix.image }}-image.*
|
||||
name: release-readiness-debian-image
|
||||
path: release-readiness-debian-image.*
|
||||
compression-level: 0
|
||||
if-no-files-found: error
|
||||
|
||||
@@ -18,7 +18,7 @@ jobs:
|
||||
version: '8.3.1'
|
||||
- uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version: '20'
|
||||
node-version: '24'
|
||||
cache: pnpm
|
||||
- run: pnpm install --frozen-lockfile
|
||||
- run: cp .env.example .env
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
# Node.js 原生部署与 Python venv
|
||||
|
||||
面板要求 Node.js >=22.17,推荐 Node.js 24,并要求该 Node 构建提供 `node:sqlite`。应用升级保留现有 Node;旧 Node 20 环境需先升级运行时。远程管理 CLI 的最低版本要求独立于面板。
|
||||
|
||||
设置 `QL_DIR` 为安装目录,`QL_DATA_DIR` 为以 `/data` 结尾的绝对持久化数据路径。
|
||||
如需隔离 Python,请在启动进程的环境中显式设置 `PYTHON_VENV_DIR`(绝对路径或相对 `QL_DIR` 的路径),例如 `export PYTHON_VENV_DIR=/srv/qinglong/.venv`。未设置时保留现有 Python prefix 行为。
|
||||
|
||||
|
||||
+28
-133
@@ -1,20 +1,11 @@
|
||||
import { executionIdPattern, executionTriggerId, receiptFinishTime } from '../shared/executionIdentity';
|
||||
import { readDailyResults } from '../shared/legacyDailyStatistics';
|
||||
import { PendingCronInstall } from '../shared/errors';
|
||||
import { triggerHistory } from '../shared/triggerHistory';
|
||||
import { previewSchedule, withNextRun } from '../shared/cronPreview';
|
||||
import { Router, Request, Response, NextFunction } from 'express';
|
||||
import { literal, Op } from 'sequelize';
|
||||
import { Container } from 'typedi';
|
||||
import { Logger } from 'winston';
|
||||
import CronService from '../services/cron';
|
||||
import CronViewService from '../services/cronView';
|
||||
import { celebrate, Joi } from 'celebrate';
|
||||
import { commonCronSchema } from '../validation/schedule';
|
||||
import {
|
||||
RunningInstanceModel,
|
||||
InstanceStatus,
|
||||
} from '../data/runningInstance';
|
||||
import { RunningInstanceModel, InstanceStatus } from '../data/runningInstance';
|
||||
import { t } from '../shared/i18n';
|
||||
import cronClient from '../schedule/client';
|
||||
|
||||
@@ -25,8 +16,17 @@ export default (app: Router) => {
|
||||
|
||||
route.use(async (req, res, next) => {
|
||||
// Keep stop/status callbacks available even when the scheduler is down.
|
||||
if (['POST', 'PUT', 'DELETE'].includes(req.method) &&
|
||||
['/', '/run', '/enable', '/disable', '/views/enable', '/views/disable'].includes(req.path)) {
|
||||
if (
|
||||
['POST', 'PUT', 'DELETE'].includes(req.method) &&
|
||||
[
|
||||
'/',
|
||||
'/run',
|
||||
'/enable',
|
||||
'/disable',
|
||||
'/views/enable',
|
||||
'/views/disable',
|
||||
].includes(req.path)
|
||||
) {
|
||||
try {
|
||||
await cronClient.readiness.ensureReady();
|
||||
} catch (error) {
|
||||
@@ -170,25 +170,14 @@ export default (app: Router) => {
|
||||
const logger: Logger = Container.get('logger');
|
||||
try {
|
||||
const cronService = Container.get(CronService);
|
||||
const result = await cronService.crontabs(req.query as any, true);
|
||||
return res.send({ code: 200, data: { ...result, data: result.data.map(withNextRun) } });
|
||||
const data = await cronService.crontabs(req.query as any);
|
||||
return res.send({ code: 200, data });
|
||||
} catch (e) {
|
||||
logger.error('🔥 error: %o', e);
|
||||
return next(e);
|
||||
}
|
||||
});
|
||||
|
||||
route.get('/preview', celebrate({ query: Joi.object({
|
||||
schedule: Joi.string().required(),
|
||||
}).unknown(true) }), (req, res) => {
|
||||
try {
|
||||
const times = previewSchedule(String(req.query.schedule), 3, Date.now());
|
||||
return res.send({ code: 200, data: { times, timezone: Intl.DateTimeFormat().resolvedOptions().timeZone } });
|
||||
} catch {
|
||||
return res.status(400).send({ code: 400, message: t('Cron表达式格式有误') });
|
||||
}
|
||||
});
|
||||
|
||||
route.get(
|
||||
'/detail',
|
||||
async (req: Request, res: Response, next: NextFunction) => {
|
||||
@@ -216,11 +205,6 @@ export default (app: Router) => {
|
||||
const data = await cronService.create(req.body);
|
||||
return res.send({ code: 200, data });
|
||||
} catch (e) {
|
||||
if (e instanceof PendingCronInstall) {
|
||||
return res.status(e.status).send({
|
||||
code: e.status, message: e.message, data: { id: e.cronId, saved: false },
|
||||
});
|
||||
}
|
||||
return next(e);
|
||||
}
|
||||
},
|
||||
@@ -246,14 +230,13 @@ export default (app: Router) => {
|
||||
route.put(
|
||||
'/stop',
|
||||
celebrate({
|
||||
headers: Joi.object({ 'idempotency-key': Joi.string().guid().optional() }).unknown(true),
|
||||
body: Joi.array().items(Joi.number().required()),
|
||||
}),
|
||||
async (req: Request, res: Response, next: NextFunction) => {
|
||||
const logger: Logger = Container.get('logger');
|
||||
try {
|
||||
const cronService = Container.get(CronService);
|
||||
const data = await cronService.stop(req.body, req.get('Idempotency-Key'));
|
||||
const data = await cronService.stop(req.body);
|
||||
return res.send({ code: 200, data });
|
||||
} catch (e) {
|
||||
return next(e);
|
||||
@@ -345,11 +328,6 @@ export default (app: Router) => {
|
||||
id: Joi.number().required(),
|
||||
}),
|
||||
query: Joi.object({
|
||||
triggerId: Joi.string().max(256).optional(),
|
||||
instanceId: Joi.number().integer().positive().optional(),
|
||||
previousPath: Joi.string().optional(),
|
||||
follow: Joi.boolean().optional(),
|
||||
cursor: Joi.string().pattern(/^\d{1,16}\.[a-f0-9]{64}$/).optional(),
|
||||
offset: Joi.number().integer().min(0).optional(),
|
||||
limit: Joi.number()
|
||||
.integer()
|
||||
@@ -365,11 +343,6 @@ export default (app: Router) => {
|
||||
try {
|
||||
const cronService = Container.get(CronService);
|
||||
const result = await cronService.log(req.params.id, {
|
||||
triggerId: req.query.triggerId as string | undefined,
|
||||
instanceId: req.query.instanceId === undefined ? undefined : Number(req.query.instanceId),
|
||||
previousPath: req.query.previousPath as string | undefined,
|
||||
follow: req.query.follow as unknown as boolean,
|
||||
cursor: req.query.cursor as string | undefined,
|
||||
offset: req.query.offset as unknown as number,
|
||||
limit: req.query.limit as unknown as number,
|
||||
tail: req.query.tail as unknown as boolean,
|
||||
@@ -378,10 +351,6 @@ export default (app: Router) => {
|
||||
code: 200,
|
||||
data: result.content,
|
||||
logStatus: result.status,
|
||||
logPath: result.logPath,
|
||||
triggerId: result.triggerId,
|
||||
cursor: result.cursor,
|
||||
reset: result.reset,
|
||||
offset: result.offset,
|
||||
nextOffset: result.nextOffset,
|
||||
total: result.total,
|
||||
@@ -416,10 +385,7 @@ export default (app: Router) => {
|
||||
route.delete(
|
||||
'/',
|
||||
celebrate({
|
||||
body: Joi.array().min(1).items(Joi.number().integer().positive(), Joi.object({
|
||||
id: Joi.number().integer().positive().required(), script: Joi.string().required(),
|
||||
revision: Joi.number().integer(), command: Joi.string(), sub_id: Joi.number().integer().allow(null),
|
||||
})),
|
||||
body: Joi.array().items(Joi.number().required()),
|
||||
}),
|
||||
async (req: Request, res: Response, next: NextFunction) => {
|
||||
const logger: Logger = Container.get('logger');
|
||||
@@ -492,8 +458,8 @@ export default (app: Router) => {
|
||||
const logger: Logger = Container.get('logger');
|
||||
try {
|
||||
const cronService = Container.get(CronService);
|
||||
const data = await cronService.getDb({ id: req.params.id }, true);
|
||||
return res.send({ code: 200, data: withNextRun(data) });
|
||||
const data = await cronService.getDb({ id: req.params.id });
|
||||
return res.send({ code: 200, data });
|
||||
} catch (e) {
|
||||
return next(e);
|
||||
}
|
||||
@@ -511,19 +477,13 @@ export default (app: Router) => {
|
||||
last_running_time: Joi.number().optional().allow(null),
|
||||
last_execution_time: Joi.number().optional().allow(null),
|
||||
exit_code: Joi.number().optional().allow(null),
|
||||
trigger_stopped: Joi.boolean().optional(),
|
||||
execution_id: Joi.string().pattern(executionIdPattern).optional(),
|
||||
trigger_id: Joi.string().pattern(/^[a-z0-9-]{1,120}$/).optional(),
|
||||
}).oxor('execution_id', 'trigger_id'),
|
||||
}),
|
||||
}),
|
||||
async (req: Request, res: Response, next: NextFunction) => {
|
||||
try {
|
||||
const cronService = Container.get(CronService);
|
||||
const { execution_id, ...body } = req.body;
|
||||
const data = await cronService.status({
|
||||
...body,
|
||||
finished_at: receiptFinishTime(req.get('X-QL-Finished-At')),
|
||||
...(execution_id && { trigger_id: executionTriggerId(execution_id) }),
|
||||
...req.body,
|
||||
status: req.body.status ? parseInt(req.body.status) : undefined,
|
||||
pid: req.body.pid ? parseInt(req.body.pid) : undefined,
|
||||
});
|
||||
@@ -534,87 +494,18 @@ export default (app: Router) => {
|
||||
},
|
||||
);
|
||||
|
||||
route.get('/:id/daily-results', celebrate({
|
||||
params: Joi.object({ id: Joi.number().integer().positive().required() }),
|
||||
}), async (req, res, next) => {
|
||||
try {
|
||||
const data = await readDailyResults(RunningInstanceModel.sequelize!, Number(req.params.id));
|
||||
return res.send({ code: 200, data });
|
||||
} catch (error) {
|
||||
return next(error);
|
||||
}
|
||||
});
|
||||
|
||||
route.get('/:id/triggers', celebrate({
|
||||
params: Joi.object({ id: Joi.number().integer().positive().required() }),
|
||||
query: Joi.object({
|
||||
offset: Joi.number().integer().min(0),
|
||||
limit: Joi.number().integer().min(1).max(26).default(25),
|
||||
ids: Joi.array().items(Joi.string().max(256)).min(1).max(25).single(),
|
||||
beforeTime: Joi.number().integer().min(0),
|
||||
beforeId: Joi.string().max(256),
|
||||
}).and('beforeTime', 'beforeId').oxor('offset', 'beforeTime', 'ids').unknown(true),
|
||||
}), async (req, res, next) => {
|
||||
try {
|
||||
const { offset, limit, beforeTime, beforeId, ids } = req.query;
|
||||
const history = triggerHistory();
|
||||
const before = beforeId ? { time: Number(beforeTime), id: String(beforeId) } : undefined;
|
||||
const data = ids
|
||||
? await history.visibleTriggers(Number(req.params.id), ids as string[])
|
||||
: await history.recent(Number(req.params.id), Number(offset || 0), Number(limit), before);
|
||||
if (req.query.withQueueWait === 'true') {
|
||||
const now = Date.now();
|
||||
return res.send({ code: 200, data: data.map(row => row.state === 'queued' && row.queued_at != null
|
||||
? { ...row, queue_wait_ms: Math.max(0, (row.dequeued_at ?? now) - row.queued_at) } : row) });
|
||||
}
|
||||
return res.send({ code: 200, data });
|
||||
} catch (err) { next(err); }
|
||||
});
|
||||
|
||||
route.get(
|
||||
'/:id/instances',
|
||||
celebrate({
|
||||
// This route historically ignored query parameters. Only validate and
|
||||
// apply cursor options when the caller explicitly requests pagination.
|
||||
query: Joi.alternatives().conditional(Joi.object({ paged: Joi.valid('true').required() }).unknown(), {
|
||||
then: Joi.object({
|
||||
limit: Joi.number().integer().min(1).max(100),
|
||||
before: Joi.number().integer().positive(),
|
||||
ids: Joi.string().pattern(/^\d+(,\d+){0,99}$/),
|
||||
}).unknown(true).oxor('ids', 'limit').oxor('ids', 'before'),
|
||||
otherwise: Joi.object().unknown(true),
|
||||
}),
|
||||
params: Joi.object({
|
||||
id: Joi.number().required(),
|
||||
}),
|
||||
}),
|
||||
async (req: Request<{ id: number }>, res: Response, next: NextFunction) => {
|
||||
try {
|
||||
// The instance row may retain a provisional end for cleanup after a restart.
|
||||
const pending = `EXISTS (SELECT 1 FROM CronTriggers t WHERE t.instance_id=RunningInstance.id
|
||||
AND (t.exit_pending=1 OR (t.state='unknown' AND t.reason='restart')))`;
|
||||
const paged = req.query.paged === 'true';
|
||||
const ids = paged && req.query.ids ? String(req.query.ids).split(',').map(Number) : undefined;
|
||||
const limit = paged && !ids ? Number(req.query.limit ?? 25) : undefined;
|
||||
const instances = await RunningInstanceModel.findAll({
|
||||
attributes: {
|
||||
exclude: ['finished_at', 'exit_code'],
|
||||
include: [
|
||||
[literal(`CASE WHEN ${pending} THEN NULL ELSE finished_at END`), 'finished_at'],
|
||||
[literal(`CASE WHEN ${pending} THEN NULL ELSE exit_code END`), 'exit_code'],
|
||||
],
|
||||
},
|
||||
where: {
|
||||
const instances = await RunningInstanceModel.find({
|
||||
cron_id: req.params.id,
|
||||
...(ids && { id: { [Op.in]: ids } }),
|
||||
...(paged && req.query.before && { id: { [Op.lt]: Number(req.query.before) } }),
|
||||
},
|
||||
order: paged ? [['id', 'DESC']] : [['started_at', 'DESC'], ['id', 'DESC']],
|
||||
...(limit && { limit: limit + 1 }),
|
||||
raw: true,
|
||||
});
|
||||
if (limit) return res.send({ code: 200, data: instances.slice(0, limit),
|
||||
next: instances.length > limit ? instances[limit - 1].id : null });
|
||||
return res.send({ code: 200, data: instances });
|
||||
} catch (e) {
|
||||
return next(e);
|
||||
@@ -630,11 +521,15 @@ export default (app: Router) => {
|
||||
instanceId: Joi.number().required(),
|
||||
}),
|
||||
}),
|
||||
async (req: Request<{ id: number; instanceId: number }>, res: Response, next: NextFunction) => {
|
||||
async (
|
||||
req: Request<{ id: number; instanceId: number }>,
|
||||
res: Response,
|
||||
next: NextFunction,
|
||||
) => {
|
||||
try {
|
||||
const cronService = Container.get(CronService);
|
||||
const data = await cronService.stopInstance(Number(req.params.id), Number(req.params.instanceId));
|
||||
return res.status(data.code).send(data);
|
||||
const data = await cronService.stopInstance(req.params.instanceId);
|
||||
return res.send(data);
|
||||
} catch (e) {
|
||||
return next(e);
|
||||
}
|
||||
|
||||
+126
-182
@@ -1,100 +1,86 @@
|
||||
import { executionIdPattern, executionTriggerId, receiptFinishTime } from '../shared/executionIdentity';
|
||||
import { oldestQueued } from '../shared/queueDiagnostics';
|
||||
import { containerResources } from '../shared/containerResources';
|
||||
import { TriggerHistory } from '../shared/triggerHistory';
|
||||
import { statistics } from '../data/statistics';
|
||||
import { Query, QuerySpec, orderBy } from '../data/queries';
|
||||
import { Router, Request, Response, NextFunction } from 'express';
|
||||
import { Container } from 'typedi';
|
||||
import { fn, col, where, Op } from 'sequelize';
|
||||
import { CrontabModel } from '../data/cron';
|
||||
import { CrontabStatModel } from '../data/cronStats';
|
||||
import {
|
||||
RunningInstanceModel,
|
||||
InstanceStatus,
|
||||
} from '../data/runningInstance';
|
||||
import { RunningInstanceModel, InstanceStatus } from '../data/runningInstance';
|
||||
import dayjs from 'dayjs';
|
||||
import os from 'os';
|
||||
import { isEmpty } from 'lodash';
|
||||
import { t, tf } from '../shared/i18n';
|
||||
|
||||
function averageElapsed(totalTime: number, runs: number, untimed: number) {
|
||||
const samples = Number(runs) - (Number(untimed) || 0);
|
||||
return samples > 0 ? Math.round(Number(totalTime) / samples) : 0;
|
||||
}
|
||||
|
||||
const route = Router();
|
||||
|
||||
export default (app: Router) => {
|
||||
app.use('/dashboard', route);
|
||||
|
||||
route.post('/record', async (req: Request, res: Response) => {
|
||||
try {
|
||||
const { ref_id, code, elapsed, trigger_id, execution_id } = req.body;
|
||||
const { ref_id, code, elapsed } = req.body;
|
||||
if (!ref_id) return res.send({ code: 400, message: 'ref_id required' });
|
||||
|
||||
if (trigger_id != null && (typeof trigger_id !== 'string' || !/^[a-z0-9-]{1,120}$/.test(trigger_id))) {
|
||||
return res.send({ code: 400 });
|
||||
const today = dayjs().format('YYYY-MM-DD');
|
||||
const isSuccess = code === 0 ? 1 : 0;
|
||||
const isFail = code !== 0 ? 1 : 0;
|
||||
const elapsedMs = (Number(elapsed) || 0) * 1000;
|
||||
const existing = await CrontabStatModel.findOne(
|
||||
{ ref_id: Number(ref_id), date: today },
|
||||
{},
|
||||
);
|
||||
if (existing) {
|
||||
await CrontabStatModel.nativeUpdate(
|
||||
{ id: existing.id },
|
||||
{
|
||||
run_count: (existing.run_count || 0) + 1,
|
||||
success_count: (existing.success_count || 0) + isSuccess,
|
||||
fail_count: (existing.fail_count || 0) + isFail,
|
||||
total_time: (existing.total_time || 0) + elapsedMs,
|
||||
max_time: Math.max(existing.max_time || 0, elapsedMs),
|
||||
},
|
||||
);
|
||||
} else {
|
||||
await CrontabStatModel.insert({
|
||||
ref_id: Number(ref_id),
|
||||
date: today,
|
||||
run_count: 1,
|
||||
success_count: isSuccess,
|
||||
fail_count: isFail,
|
||||
total_time: elapsedMs,
|
||||
max_time: elapsedMs,
|
||||
});
|
||||
}
|
||||
if (execution_id !== undefined && (trigger_id !== undefined ||
|
||||
typeof execution_id !== 'string' || !executionIdPattern.test(execution_id))) return res.send({ code: 400 });
|
||||
const id = execution_id ? executionTriggerId(execution_id) : trigger_id;
|
||||
// Old wrappers also send a status receipt with the process identity.
|
||||
// A stats-only retry cannot be distinguished from another identical run.
|
||||
if (!id) return res.send({ code: 200, data: { counted: false, reason: 'missing_execution_identity' } });
|
||||
const exitCode = typeof code === 'string' && /^-?\d+$/.test(code) ? Number(code) : code;
|
||||
const elapsedMs = Number(elapsed ?? 0) * 1000;
|
||||
if (!Number.isInteger(exitCode) || !Number.isSafeInteger(elapsedMs) || elapsedMs < 0) {
|
||||
return res.send({ code: 400, message: 'invalid exit code or elapsed time' });
|
||||
}
|
||||
await new TriggerHistory(CrontabStatModel.sequelize!).recordShellResult(id, Number(ref_id), exitCode, elapsedMs, Date.now(), receiptFinishTime(req.get('X-QL-Finished-At')));
|
||||
res.send({ code: 200 });
|
||||
} catch (e) {
|
||||
res.send({ code: 500 });
|
||||
}
|
||||
});
|
||||
|
||||
route.get(
|
||||
'/overview',
|
||||
async (req: Request, res: Response, next: NextFunction) => {
|
||||
try {
|
||||
const today = dayjs().format('YYYY-MM-DD');
|
||||
|
||||
const [total, enabled, disabled, stats, triggers] = await Promise.all([
|
||||
CrontabModel.count(),
|
||||
CrontabModel.count({ where: { isDisabled: 0 } }),
|
||||
CrontabModel.count({ where: { isDisabled: 1 } }),
|
||||
CrontabStatModel.findOne({
|
||||
attributes: [
|
||||
[fn('SUM', col('run_count')), 'total_runs'],
|
||||
[fn('SUM', col('success_count')), 'total_success'],
|
||||
[fn('SUM', col('fail_count')), 'total_fail'],
|
||||
[fn('SUM', col('untimed_count')), 'untimed_count'],
|
||||
[fn('SUM', col('total_time')), 'total_time'],
|
||||
],
|
||||
where: { date: today },
|
||||
raw: true,
|
||||
}),
|
||||
new TriggerHistory(CrontabStatModel.sequelize!).metrics(dayjs().startOf('day').valueOf()),
|
||||
const [total, enabled, disabled, stats] = await Promise.all([
|
||||
CrontabModel.count({}),
|
||||
CrontabModel.count({ isDisabled: 0 }),
|
||||
CrontabModel.count({ isDisabled: 1 }),
|
||||
statistics.totals(today),
|
||||
]);
|
||||
|
||||
const row = stats as any;
|
||||
const totalRuns = Number(row?.total_runs) || 0;
|
||||
const totalSuccess = Number(row?.total_success) || 0;
|
||||
const totalFail = Number(row?.total_fail) || 0;
|
||||
const totalTime = Number(row?.total_time) || 0;
|
||||
|
||||
res.send({
|
||||
code: 200,
|
||||
data: {
|
||||
total,
|
||||
enabled,
|
||||
disabled,
|
||||
triggers,
|
||||
todayRuns: totalRuns,
|
||||
todaySuccess: totalSuccess,
|
||||
todayFail: totalFail,
|
||||
todayStopped: totalRuns - totalSuccess - totalFail,
|
||||
successRate: totalRuns > 0 ? ((totalSuccess / totalRuns) * 100).toFixed(1) : '0',
|
||||
avgTime: averageElapsed(totalTime,totalRuns,row?.untimed_count),
|
||||
successRate:
|
||||
totalRuns > 0
|
||||
? ((totalSuccess / totalRuns) * 100).toFixed(1)
|
||||
: '0',
|
||||
avgTime: totalRuns > 0 ? Math.round(totalTime / totalRuns) : 0,
|
||||
},
|
||||
});
|
||||
} catch (e) {
|
||||
@@ -102,25 +88,25 @@ export default (app: Router) => {
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
for (const isSuccess of [false, true]) {
|
||||
route.get(
|
||||
isSuccess ? '/successes' : '/failures',
|
||||
async (req: Request, res: Response, next: NextFunction) => {
|
||||
try {
|
||||
const countColumn = isSuccess ? 'success_count' : 'fail_count';
|
||||
const rows = (await CrontabStatModel.findAll({
|
||||
attributes: ['ref_id', [fn('SUM', col(countColumn)), 'result_count']],
|
||||
where: { date: dayjs().format('YYYY-MM-DD'), [countColumn]: { [Op.gt]: 0 } },
|
||||
group: ['ref_id'],
|
||||
order: [[fn('SUM', col(countColumn)), 'DESC'], ['ref_id', 'ASC']],
|
||||
raw: true,
|
||||
})) as any[];
|
||||
const crons = rows.length > 0 ? await CrontabModel.findAll({
|
||||
attributes: ['id', 'name', 'command'],
|
||||
where: { id: { [Op.in]: rows.map((row) => Number(row.ref_id)) } },
|
||||
raw: true,
|
||||
}) : [];
|
||||
const rows = (await statistics.results(
|
||||
dayjs().format('YYYY-MM-DD'),
|
||||
countColumn,
|
||||
)) as any[];
|
||||
const crons =
|
||||
rows.length > 0
|
||||
? await CrontabModel.find(
|
||||
{ id: { ['$in']: rows.map((row) => Number(row.ref_id)) } },
|
||||
{
|
||||
fields: ['id', 'name', 'command'],
|
||||
},
|
||||
)
|
||||
: [];
|
||||
const cronMap = new Map(crons.map((cron) => [cron.id, cron]));
|
||||
res.send({
|
||||
code: 200,
|
||||
@@ -131,7 +117,9 @@ export default (app: Router) => {
|
||||
id,
|
||||
name: cron?.name || cron?.command || tf('任务#%s', id),
|
||||
command: cron?.command || '',
|
||||
[isSuccess ? 'successCount' : 'failCount']: Number(row.result_count),
|
||||
[isSuccess ? 'successCount' : 'failCount']: Number(
|
||||
row.result_count,
|
||||
),
|
||||
deleted: !cron,
|
||||
};
|
||||
}),
|
||||
@@ -142,7 +130,6 @@ export default (app: Router) => {
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
route.get(
|
||||
'/trend',
|
||||
async (req: Request, res: Response, next: NextFunction) => {
|
||||
@@ -152,22 +139,7 @@ export default (app: Router) => {
|
||||
for (let i = days - 1; i >= 0; i--) {
|
||||
dates.push(dayjs().subtract(i, 'day').format('YYYY-MM-DD'));
|
||||
}
|
||||
|
||||
const rows = (await CrontabStatModel.findAll({
|
||||
attributes: [
|
||||
'date',
|
||||
[fn('SUM', col('run_count')), 'total_runs'],
|
||||
[fn('SUM', col('success_count')), 'total_success'],
|
||||
[fn('SUM', col('fail_count')), 'total_fail'],
|
||||
],
|
||||
where: {
|
||||
date: { [Op.in]: dates },
|
||||
},
|
||||
group: ['date'],
|
||||
order: [['date', 'ASC']],
|
||||
raw: true,
|
||||
})) as any[];
|
||||
|
||||
const rows = (await statistics.trend(dates)) as any[];
|
||||
const dataMap: Record<string, any> = {};
|
||||
rows.forEach((r: any) => {
|
||||
dataMap[r.date] = {
|
||||
@@ -176,134 +148,95 @@ export default (app: Router) => {
|
||||
fail: Number(r.total_fail) || 0,
|
||||
};
|
||||
});
|
||||
|
||||
const data = dates.map((d) => ({
|
||||
date: dayjs(d).format('MM-DD'),
|
||||
...(dataMap[d] || { total: 0, success: 0, fail: 0 }),
|
||||
}));
|
||||
|
||||
res.send({ code: 200, data });
|
||||
} catch (e) {
|
||||
next(e);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
route.get(
|
||||
'/top-time',
|
||||
async (req: Request, res: Response, next: NextFunction) => {
|
||||
try {
|
||||
const today = dayjs().format('YYYY-MM-DD');
|
||||
|
||||
const rows = (await CrontabStatModel.findAll({
|
||||
attributes: [
|
||||
'ref_id',
|
||||
[fn('SUM', col('untimed_count')), 'untimed_count'],
|
||||
[fn('SUM', col('total_time')), 'total_time'],
|
||||
[fn('SUM', col('run_count')), 'run_count'],
|
||||
[fn('MAX', col('max_time')), 'max_time'],
|
||||
],
|
||||
where: { date: today, run_count: { [Op.gt]: 0 } },
|
||||
group: ['ref_id'],
|
||||
order: [[fn('SUM', col('total_time')), 'DESC']],
|
||||
limit: 5,
|
||||
raw: true,
|
||||
})) as any[];
|
||||
|
||||
const rows = (await statistics.ranking(today, 'total_time')) as any[];
|
||||
const ids = rows.map((r) => Number(r.ref_id));
|
||||
const crons = await CrontabModel.findAll({
|
||||
where: { id: { [Op.in]: ids } },
|
||||
raw: true,
|
||||
});
|
||||
const crons = await CrontabModel.find({ id: { ['$in']: ids } }, {});
|
||||
const nameMap: Record<number, string> = {};
|
||||
crons.forEach((c: any) => { nameMap[c.id] = c.name || c.command; });
|
||||
|
||||
crons.forEach((c: any) => {
|
||||
nameMap[c.id] = c.name || c.command;
|
||||
});
|
||||
const data = rows.map((r: any, i) => ({
|
||||
rank: i + 1,
|
||||
name: nameMap[Number(r.ref_id)] || tf('任务#%s', r.ref_id),
|
||||
avgTime: averageElapsed(r.total_time,r.run_count,r.untimed_count),
|
||||
avgTime: Math.round(Number(r.total_time) / Number(r.run_count)),
|
||||
maxTime: Number(r.max_time),
|
||||
}));
|
||||
|
||||
res.send({ code: 200, data });
|
||||
} catch (e) {
|
||||
next(e);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
route.get(
|
||||
'/top-count',
|
||||
async (req: Request, res: Response, next: NextFunction) => {
|
||||
try {
|
||||
const today = dayjs().format('YYYY-MM-DD');
|
||||
|
||||
const rows = (await CrontabStatModel.findAll({
|
||||
attributes: [
|
||||
'ref_id',
|
||||
[fn('SUM', col('run_count')), 'run_count'],
|
||||
[fn('SUM', col('untimed_count')), 'untimed_count'],
|
||||
[fn('SUM', col('total_time')), 'total_time'],
|
||||
[fn('SUM', col('success_count')), 'success_count'],
|
||||
],
|
||||
where: { date: today, run_count: { [Op.gt]: 0 } },
|
||||
group: ['ref_id'],
|
||||
order: [[fn('SUM', col('run_count')), 'DESC']],
|
||||
limit: 5,
|
||||
raw: true,
|
||||
})) as any[];
|
||||
|
||||
const rows = (await statistics.ranking(today, 'run_count')) as any[];
|
||||
const ids = rows.map((r) => Number(r.ref_id));
|
||||
const crons = await CrontabModel.findAll({
|
||||
where: { id: { [Op.in]: ids } },
|
||||
raw: true,
|
||||
});
|
||||
const crons = await CrontabModel.find({ id: { ['$in']: ids } }, {});
|
||||
const nameMap: Record<number, string> = {};
|
||||
crons.forEach((c: any) => { nameMap[c.id] = c.name || c.command; });
|
||||
|
||||
crons.forEach((c: any) => {
|
||||
nameMap[c.id] = c.name || c.command;
|
||||
});
|
||||
const data = rows.map((r: any, i) => ({
|
||||
rank: i + 1,
|
||||
name: nameMap[Number(r.ref_id)] || tf('任务#%s', r.ref_id),
|
||||
runCount: Number(r.run_count),
|
||||
avgTime: averageElapsed(r.total_time,r.run_count,r.untimed_count),
|
||||
avgTime: Math.round(Number(r.total_time) / Number(r.run_count)),
|
||||
successRate:
|
||||
Number(r.run_count) > 0
|
||||
? ((Number(r.success_count) / Number(r.run_count)) * 100).toFixed(1)
|
||||
? ((Number(r.success_count) / Number(r.run_count)) * 100).toFixed(
|
||||
1,
|
||||
)
|
||||
: '0',
|
||||
}));
|
||||
|
||||
res.send({ code: 200, data });
|
||||
} catch (e) {
|
||||
next(e);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
route.get(
|
||||
'/runtime',
|
||||
async (req: Request, res: Response, next: NextFunction) => {
|
||||
try {
|
||||
const queued = await new TriggerHistory(CrontabModel.sequelize!).queueCounts();
|
||||
const runningInstances = await RunningInstanceModel.findAll({
|
||||
where: {
|
||||
const runningInstances = await RunningInstanceModel.find(
|
||||
{
|
||||
status: InstanceStatus.running,
|
||||
},
|
||||
raw: true,
|
||||
});
|
||||
|
||||
{},
|
||||
);
|
||||
const queuedCrons = await CrontabModel.find(
|
||||
{
|
||||
status: 3, // queued
|
||||
},
|
||||
{},
|
||||
);
|
||||
// Fetch cron names for running instances
|
||||
const cronIds = [
|
||||
...new Set(runningInstances.map((i: any) => i.cron_id)),
|
||||
];
|
||||
const crons =
|
||||
cronIds.length > 0
|
||||
? await CrontabModel.findAll({
|
||||
where: { id: cronIds },
|
||||
raw: true,
|
||||
})
|
||||
? await CrontabModel.find({ id: cronIds }, {})
|
||||
: [];
|
||||
const cronMap = new Map(crons.map((c: any) => [c.id, c]));
|
||||
|
||||
const now = dayjs().unix();
|
||||
const running = runningInstances.map((inst: any) => {
|
||||
const cron = cronMap.get(inst.cron_id);
|
||||
@@ -316,26 +249,23 @@ export default (app: Router) => {
|
||||
logPath: inst.log_path,
|
||||
};
|
||||
});
|
||||
|
||||
const dayAgo = dayjs().subtract(24, 'hour').unix();
|
||||
const idleTasks = await CrontabModel.findAll({
|
||||
where: {
|
||||
const idleTasks = await CrontabModel.find(
|
||||
{
|
||||
isDisabled: 0,
|
||||
status: 1,
|
||||
last_execution_time: { [Op.lt]: dayAgo },
|
||||
last_execution_time: { ['$lt']: dayAgo },
|
||||
},
|
||||
order: [['last_execution_time', 'ASC']],
|
||||
{
|
||||
orderBy: orderBy([['last_execution_time', 'ASC']]),
|
||||
limit: 5,
|
||||
raw: true,
|
||||
});
|
||||
|
||||
},
|
||||
);
|
||||
res.send({
|
||||
code: 200,
|
||||
data: {
|
||||
runningCount: running.length,
|
||||
queuedCount: queued.triggers,
|
||||
queuedTasks: queued.tasks,
|
||||
oldestQueued: queued.triggers ? await oldestQueued(CrontabModel.sequelize!) : [],
|
||||
queuedCount: queuedCrons.length,
|
||||
running,
|
||||
idleTasks: idleTasks.map((c: any) => ({
|
||||
id: c.id,
|
||||
@@ -351,60 +281,69 @@ export default (app: Router) => {
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
route.get(
|
||||
'/labels',
|
||||
async (req: Request, res: Response, next: NextFunction) => {
|
||||
try {
|
||||
const today = dayjs().format('YYYY-MM-DD');
|
||||
const [crons, stats] = (await Promise.all([
|
||||
CrontabModel.findAll({ where: { isDisabled: 0 }, raw: true }),
|
||||
CrontabStatModel.findAll({ where: { date: today }, raw: true }),
|
||||
]));
|
||||
|
||||
const [crons, stats] = await Promise.all([
|
||||
CrontabModel.find({ isDisabled: 0 }, {}),
|
||||
CrontabStatModel.find({ date: today }, {}),
|
||||
]);
|
||||
const statMap: Record<number, any> = {};
|
||||
stats.forEach((s: any) => { statMap[s.ref_id] = s; });
|
||||
|
||||
const labelMap: Record<string, { count: number; runs: number; success: number; untimed: number; totalTime: number }> = {};
|
||||
stats.forEach((s: any) => {
|
||||
statMap[s.ref_id] = s;
|
||||
});
|
||||
const labelMap: Record<
|
||||
string,
|
||||
{
|
||||
count: number;
|
||||
runs: number;
|
||||
success: number;
|
||||
totalTime: number;
|
||||
}
|
||||
> = {};
|
||||
crons.forEach((c) => {
|
||||
let rawLabels = c.labels;
|
||||
if (typeof rawLabels === 'string') rawLabels = JSON.parse(rawLabels);
|
||||
const labels: string[] = Array.isArray(rawLabels)
|
||||
? [...new Set((rawLabels as string[]).filter((l: string) => !isEmpty(l)))]
|
||||
? [
|
||||
...new Set(
|
||||
(rawLabels as string[]).filter((l: string) => !isEmpty(l)),
|
||||
),
|
||||
]
|
||||
: [];
|
||||
if (labels.length === 0) {
|
||||
labels.push(t('未分类'));
|
||||
}
|
||||
const st = statMap[c.id!];
|
||||
labels.forEach((label: string) => {
|
||||
if (!labelMap[label]) labelMap[label] = { count: 0, runs: 0, success: 0, untimed: 0, totalTime: 0 };
|
||||
if (!labelMap[label])
|
||||
labelMap[label] = { count: 0, runs: 0, success: 0, totalTime: 0 };
|
||||
labelMap[label].count += 1;
|
||||
if (st) {
|
||||
labelMap[label].runs += Number(st.run_count) || 0;
|
||||
labelMap[label].success += Number(st.success_count) || 0;
|
||||
labelMap[label].untimed += Number(st.untimed_count) || 0;
|
||||
labelMap[label].totalTime += Number(st.total_time) || 0;
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
const data = Object.entries(labelMap)
|
||||
.map(([label, v]) => ({
|
||||
label,
|
||||
count: v.count,
|
||||
todayRuns: v.runs,
|
||||
successRate: v.runs > 0 ? ((v.success / v.runs) * 100).toFixed(1) : '0',
|
||||
avgTime: averageElapsed(v.totalTime,v.runs,v.untimed),
|
||||
successRate:
|
||||
v.runs > 0 ? ((v.success / v.runs) * 100).toFixed(1) : '0',
|
||||
avgTime: v.runs > 0 ? Math.round(v.totalTime / v.runs) : 0,
|
||||
}))
|
||||
.sort((a, b) => b.todayRuns - a.todayRuns);
|
||||
|
||||
res.send({ code: 200, data });
|
||||
} catch (e) {
|
||||
next(e);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
route.get(
|
||||
'/system',
|
||||
async (req: Request, res: Response, next: NextFunction) => {
|
||||
@@ -415,10 +354,15 @@ export default (app: Router) => {
|
||||
data: {
|
||||
platform: os.platform(),
|
||||
uptime: Math.floor(process.uptime()),
|
||||
...containerResources(),
|
||||
memTotal: os.totalmem(),
|
||||
memFree: os.freemem(),
|
||||
memUsagePercent: ((1 - os.freemem() / os.totalmem()) * 100).toFixed(
|
||||
1,
|
||||
),
|
||||
heapUsed: Math.round(memUsage.heapUsed / 1024 / 1024),
|
||||
heapTotal: Math.round(memUsage.heapTotal / 1024 / 1024),
|
||||
loadAvg: os.loadavg().map((v) => Number(v.toFixed(2))),
|
||||
cpus: os.cpus().length,
|
||||
},
|
||||
});
|
||||
} catch (e) {
|
||||
|
||||
+2
-64
@@ -11,7 +11,8 @@ export default (app: Router) => {
|
||||
route.get(
|
||||
'/',
|
||||
celebrate({
|
||||
query: Joi.object({
|
||||
query:
|
||||
Joi.object({
|
||||
searchValue: Joi.string().optional().allow(''),
|
||||
type: Joi.string().optional().allow(''),
|
||||
status: Joi.string().optional().allow(''),
|
||||
@@ -30,69 +31,6 @@ export default (app: Router) => {
|
||||
},
|
||||
);
|
||||
|
||||
route.post(
|
||||
'/refresh',
|
||||
celebrate({
|
||||
body: Joi.object({
|
||||
type: Joi.string().valid('nodejs', 'python3').required(),
|
||||
}),
|
||||
}),
|
||||
async (req: Request, res: Response, next: NextFunction) => {
|
||||
try {
|
||||
const dependenceService = Container.get(DependenceService);
|
||||
const { job, accepted } = dependenceService.startRefresh(req.body.type);
|
||||
if (!accepted) {
|
||||
return res.status(409).send({
|
||||
code: 409,
|
||||
message: 'Another dependency refresh is already running',
|
||||
});
|
||||
}
|
||||
return res.send({ code: 200, data: job });
|
||||
} catch (e) {
|
||||
return next(e);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
route.get(
|
||||
'/refresh/active',
|
||||
async (_req: Request, res: Response, next: NextFunction) => {
|
||||
try {
|
||||
const dependenceService = Container.get(DependenceService);
|
||||
res.set('Cache-Control', 'no-store');
|
||||
return res.send({
|
||||
code: 200,
|
||||
data: dependenceService.getActiveRefreshJob() || null,
|
||||
});
|
||||
} catch (e) {
|
||||
return next(e);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
route.get(
|
||||
'/refresh/:id',
|
||||
celebrate({
|
||||
params: Joi.object({ id: Joi.string().uuid().required() }),
|
||||
}),
|
||||
async (req: Request, res: Response, next: NextFunction) => {
|
||||
try {
|
||||
const dependenceService = Container.get(DependenceService);
|
||||
const job = dependenceService.getRefreshJob(req.params.id);
|
||||
if (!job) {
|
||||
return res.status(404).send({
|
||||
code: 404,
|
||||
message: 'Dependency refresh job not found',
|
||||
});
|
||||
}
|
||||
res.set('Cache-Control', 'no-store');
|
||||
return res.send({ code: 200, data: job });
|
||||
} catch (e) {
|
||||
return next(e);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
route.post(
|
||||
'/',
|
||||
celebrate({
|
||||
|
||||
@@ -20,6 +20,7 @@ export default (app: Router) => {
|
||||
res.status(500).send({
|
||||
code: 500,
|
||||
message: 'Health check failed',
|
||||
error: err.message,
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
+1
-10
@@ -1,4 +1,3 @@
|
||||
import { directoryCheckHandler, directoryPageHandler } from '../shared/directoryPageRoute';
|
||||
import { celebrate, Joi } from 'celebrate';
|
||||
import { NextFunction, Request, Response, Router } from 'express';
|
||||
import { Container } from 'typedi';
|
||||
@@ -18,8 +17,6 @@ const blacklist = ['.tmp'];
|
||||
|
||||
export default (app: Router) => {
|
||||
app.use('/logs', route);
|
||||
route.get('/entries', ...directoryPageHandler(() => config.logPath, blacklist, true));
|
||||
route.post('/entries/check', ...directoryCheckHandler(() => config.logPath, blacklist));
|
||||
|
||||
route.get('/', async (req: Request, res: Response, next: NextFunction) => {
|
||||
const logger: Logger = Container.get('logger');
|
||||
@@ -41,8 +38,6 @@ export default (app: Router) => {
|
||||
query: Joi.object({
|
||||
path: Joi.string().allow('').optional(),
|
||||
file: Joi.string().required(),
|
||||
follow: Joi.boolean().optional(),
|
||||
cursor: Joi.string().pattern(/^\d{1,16}\.[a-f0-9]{64}$/).optional(),
|
||||
offset: Joi.number().integer().min(0).optional(),
|
||||
limit: Joi.number()
|
||||
.integer()
|
||||
@@ -72,18 +67,14 @@ export default (app: Router) => {
|
||||
});
|
||||
|
||||
const chunk = await readLogChunk(finalPath, {
|
||||
follow: req.query.follow as unknown as boolean,
|
||||
cursor: req.query.cursor as string | undefined,
|
||||
offset: req.query.offset as unknown as number,
|
||||
limit: req.query.limit as unknown as number,
|
||||
tail: req.query.tail as unknown as boolean,
|
||||
});
|
||||
res.send({
|
||||
code: 200,
|
||||
data: req.query.follow ? chunk.content : removeAnsi(chunk.content),
|
||||
data: removeAnsi(chunk.content),
|
||||
logStatus: runningInstance ? 'running' : undefined,
|
||||
cursor: chunk.cursor,
|
||||
reset: chunk.reset,
|
||||
offset: chunk.offset,
|
||||
nextOffset: chunk.nextOffset,
|
||||
total: chunk.total,
|
||||
|
||||
+2
-2
@@ -27,7 +27,7 @@ export default (app: Router) => {
|
||||
celebrate({
|
||||
body: Joi.object({
|
||||
name: Joi.string().optional().allow('').disallow('system'),
|
||||
scopes: Joi.array().items(Joi.string().required().invalid('apps')),
|
||||
scopes: Joi.array().items(Joi.string().required()),
|
||||
}),
|
||||
}),
|
||||
async (req: Request, res: Response, next: NextFunction) => {
|
||||
@@ -47,7 +47,7 @@ export default (app: Router) => {
|
||||
celebrate({
|
||||
body: Joi.object({
|
||||
name: Joi.string().optional().allow(''),
|
||||
scopes: Joi.array().items(Joi.string().invalid('apps')),
|
||||
scopes: Joi.array().items(Joi.string()),
|
||||
id: Joi.number().required(),
|
||||
}),
|
||||
}),
|
||||
|
||||
+8
-12
@@ -1,4 +1,3 @@
|
||||
import { directoryCheckHandler, directoryPageHandler } from '../shared/directoryPageRoute';
|
||||
import { randomUUID } from 'crypto';
|
||||
import { resolveFileAccess } from '../shared/fileAccess';
|
||||
import { fileExist, readDirs, readDir, rmPath, IFile } from '../config/util';
|
||||
@@ -19,14 +18,6 @@ import {
|
||||
HistoryUnavailableError,
|
||||
} from '../shared/scriptHistory';
|
||||
const route = Router();
|
||||
const blacklist = [
|
||||
'node_modules',
|
||||
'.git',
|
||||
'.pnpm',
|
||||
'pnpm-lock.yaml',
|
||||
'yarn.lock',
|
||||
'package-lock.json',
|
||||
];
|
||||
|
||||
function isPathAllowed(targetPath: string): boolean {
|
||||
const resolved = path.resolve(targetPath);
|
||||
@@ -84,8 +75,6 @@ const upload = multer({ storage: storage });
|
||||
|
||||
export default (app: Router) => {
|
||||
app.use('/scripts', route);
|
||||
route.get('/entries', ...directoryPageHandler(() => config.scriptPath, blacklist, false));
|
||||
route.post('/entries/check', ...directoryCheckHandler(() => config.scriptPath, blacklist));
|
||||
|
||||
route.get(
|
||||
'/',
|
||||
@@ -98,7 +87,14 @@ export default (app: Router) => {
|
||||
const logger: Logger = Container.get('logger');
|
||||
try {
|
||||
let result: IFile[] = [];
|
||||
|
||||
const blacklist = [
|
||||
'node_modules',
|
||||
'.git',
|
||||
'.pnpm',
|
||||
'pnpm-lock.yaml',
|
||||
'yarn.lock',
|
||||
'package-lock.json',
|
||||
];
|
||||
if (req.query.path) {
|
||||
if (
|
||||
!resolveFileAccess(config.scriptPath, [req.query.path as string])
|
||||
|
||||
+1
-3
@@ -4,7 +4,6 @@ import { Logger } from 'winston';
|
||||
import * as fs from 'fs/promises';
|
||||
import config from '../config';
|
||||
import SystemService from '../services/system';
|
||||
import { containerResources } from '../shared/containerResources';
|
||||
import { celebrate, Joi } from 'celebrate';
|
||||
import UserService from '../services/user';
|
||||
import { t } from '../shared/i18n';
|
||||
@@ -63,8 +62,7 @@ export default (app: Router) => {
|
||||
try {
|
||||
const systemService = Container.get(SystemService);
|
||||
const data = await systemService.getSystemConfig();
|
||||
res.send({ code: 200, data: { ...data, effectiveCronConcurrency: systemService.cronConcurrency,
|
||||
availableCpus: containerResources().cpus } });
|
||||
res.send({ code: 200, data });
|
||||
} catch (e) {
|
||||
return next(e);
|
||||
}
|
||||
|
||||
@@ -310,6 +310,20 @@ export default (app: Router) => {
|
||||
},
|
||||
);
|
||||
|
||||
route.put(
|
||||
'/notification/init',
|
||||
async (req: Request, res: Response, next: NextFunction) => {
|
||||
const logger: Logger = Container.get('logger');
|
||||
try {
|
||||
const userService = Container.get(UserService);
|
||||
const result = await userService.updateNotificationMode(req.body);
|
||||
res.send(result);
|
||||
} catch (e) {
|
||||
return next(e);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
route.put(
|
||||
'/avatar',
|
||||
upload.single('avatar'),
|
||||
|
||||
-31
@@ -138,19 +138,7 @@ class Application {
|
||||
workerEnv.pmx = 'false';
|
||||
}
|
||||
const worker = cluster.fork(workerEnv);
|
||||
if (serviceType === 'grpc') worker.on('message', (msg) => {
|
||||
if (msg === 'crontab-install-failed' && this.httpWorker?.isConnected()) {
|
||||
this.httpWorker.send('reregister-crons');
|
||||
}
|
||||
});
|
||||
|
||||
if (serviceType === 'http') worker.on('message', (msg) => {
|
||||
if (msg?.type !== 'cancel-queued-triggers') return;
|
||||
for (const [id, meta] of this.workerMetadataMap) {
|
||||
const target = cluster.workers?.[id];
|
||||
if (meta.serviceType === 'grpc' && target?.isConnected()) target.send(msg);
|
||||
}
|
||||
});
|
||||
this.workerMetadataMap.set(worker.id, {
|
||||
id: worker.id,
|
||||
pid: worker.process.pid!,
|
||||
@@ -229,21 +217,8 @@ class Application {
|
||||
Logger.info(`[boot] ${serviceType} worker started (PID: ${process.pid})`);
|
||||
|
||||
try {
|
||||
const { triggerHistory } = await import('./shared/triggerHistory');
|
||||
const history = triggerHistory();
|
||||
await history.interrupt(serviceType);
|
||||
if (serviceType === 'http') {
|
||||
await this.startHttpService();
|
||||
const retryExits = async () => {
|
||||
try {
|
||||
await history.retryPendingExits();
|
||||
} catch (error) {
|
||||
Logger.error(`[scheduler] Exit receipt retry failed: ${errStack(error)}`);
|
||||
} finally {
|
||||
if (!this.isShuttingDown) setTimeout(retryExits, 15000).unref();
|
||||
}
|
||||
};
|
||||
setTimeout(retryExits, 15000).unref();
|
||||
} else {
|
||||
await this.startGrpcService();
|
||||
}
|
||||
@@ -290,10 +265,6 @@ class Application {
|
||||
process.on('message', async (msg) => {
|
||||
if (msg === 'shutdown') {
|
||||
this.gracefulShutdown(serviceType);
|
||||
} else if (serviceType === 'grpc' && typeof msg === 'object' && msg &&
|
||||
'type' in msg && msg.type === 'cancel-queued-triggers' && 'ids' in msg && Array.isArray(msg.ids)) {
|
||||
const { cancelWaitingTriggers } = await import('./shared/runCron');
|
||||
cancelWaitingTriggers(msg.ids);
|
||||
} else if (serviceType === 'http' &&
|
||||
(msg === 'reregister-crons' || msg === 'scheduler-unavailable')) {
|
||||
const { default: cronClient } = await import('./schedule/client');
|
||||
@@ -311,8 +282,6 @@ class Application {
|
||||
this.isShuttingDown = true;
|
||||
|
||||
try {
|
||||
const { triggerHistory } = await import('./shared/triggerHistory');
|
||||
await triggerHistory().interrupt(serviceType);
|
||||
if (serviceType === 'http') {
|
||||
await this.httpServerService?.shutdown();
|
||||
} else {
|
||||
|
||||
@@ -1,19 +1,16 @@
|
||||
import { errStack } from '../shared/errors';
|
||||
|
||||
// Also terminate if the primary disappears without forwarding a signal.
|
||||
const onParentDisconnect = () => process.exit(1);
|
||||
process.once('disconnect', onParentDisconnect);
|
||||
|
||||
async function initializeDatabase() {
|
||||
const { sequelize } = await import('../data');
|
||||
const { database } = await import('../data');
|
||||
try {
|
||||
const { default: loadDatabase } = await import('../loaders/db');
|
||||
await loadDatabase();
|
||||
} finally {
|
||||
await sequelize.close();
|
||||
await database.close();
|
||||
}
|
||||
}
|
||||
|
||||
initializeDatabase()
|
||||
.catch((error) => {
|
||||
console.error(`[boot] Database initialization failed:\n${errStack(error)}`);
|
||||
|
||||
@@ -1,61 +0,0 @@
|
||||
import { storageFull, writeExit } from '../shared/managedExit.cjs';
|
||||
import { QueryTypes } from 'sequelize';
|
||||
import { randomUUID } from 'crypto';
|
||||
import { sequelize } from '../data';
|
||||
import { systemOwner, TriggerHistory } from '../shared/triggerHistory';
|
||||
|
||||
async function receipt() {
|
||||
const [action, task, pid, id, status, end] = process.argv.slice(2);
|
||||
const history = new TriggerHistory(sequelize);
|
||||
if (action === 'start') {
|
||||
await history.recoverSystemOwners(Number(task));
|
||||
const triggerId = id || `system-${task}-${randomUUID()}`;
|
||||
const owner = systemOwner(Number(pid));
|
||||
const command = status ? systemOwner(Number(status)) : owner;
|
||||
const at = Number(process.env.QL_SYSTEM_ENTERED);
|
||||
const rule = process.env.QL_SYSTEM_RULE;
|
||||
const dispatched = Number(process.env.QL_SYSTEM_DISPATCHED) * 1000;
|
||||
const dispatch = Number.isSafeInteger(dispatched) && dispatched > 0 && dispatched <= at ? dispatched : undefined;
|
||||
const wrapper = rule && Number.isSafeInteger(at) && at > 0 && at <= Date.now() ? { rule, at, dispatch } : undefined;
|
||||
const acquired = await history.startSystem(triggerId, Number(task), owner, command, wrapper);
|
||||
if (!acquired) process.exitCode = 75;
|
||||
else if (!id) process.stdout.write(triggerId);
|
||||
} else if (action === 'finish') {
|
||||
// The live wrapper inherited both IDs from the start it just claimed. A
|
||||
// standalone retry must match the registered system task before writing.
|
||||
const fromWrapper = process.env.QL_TRIGGER_ID === id && process.env.ID === task;
|
||||
if (!fromWrapper || !id?.startsWith(`system-${Number(task)}-`)) {
|
||||
const [registered] = await sequelize.query(
|
||||
`SELECT 1 FROM CronTriggers WHERE id=$id AND cron_id=$task AND source='system' AND owner LIKE 'crond:%'
|
||||
UNION ALL SELECT 1 FROM CronLegacyExitBookings WHERE trigger_id=$id AND cron_id=$task AND source='system' LIMIT 1`,
|
||||
{ bind: { id, task: Number(task) }, type: QueryTypes.SELECT });
|
||||
if (!registered) return;
|
||||
}
|
||||
const code = Number(status);
|
||||
const finishedAt = end && /^\d{13}$/.test(end) && Number(end) <= Date.now() ? Number(end) : undefined;
|
||||
const bound = fromWrapper && finishedAt !== undefined;
|
||||
let journaled = false;
|
||||
if (bound) {
|
||||
try { writeExit(id, code, null, finishedAt); journaled = true; }
|
||||
catch (error) {
|
||||
if (!storageFull(error)) throw error;
|
||||
console.error('[crond] Receipt storage full; settling the observed exit in SQLite:', error);
|
||||
}
|
||||
}
|
||||
try {
|
||||
await history.complete(id, code === 0 ? 'finished' : 'failed', null, code, finishedAt,
|
||||
bound ? { version: 1, code, signal: null, time: finishedAt } : finishedAt === undefined ? undefined : 'legacy');
|
||||
} catch (error) {
|
||||
if (!journaled || !storageFull(error)) throw error;
|
||||
// The regular recovery pass will settle the receipt after space returns.
|
||||
}
|
||||
} else {
|
||||
throw new Error('Unknown crond receipt action');
|
||||
}
|
||||
}
|
||||
|
||||
receipt().catch((error) => {
|
||||
console.error('[crond] Failed to persist execution receipt:', error);
|
||||
// At start, 75 means that another execution already owns the slot.
|
||||
process.exitCode = process.argv[2] === 'finish' && storageFull(error) ? 75 : 1;
|
||||
}).finally(() => sequelize.close());
|
||||
@@ -3,11 +3,12 @@
|
||||
import 'reflect-metadata';
|
||||
import dns from 'dns';
|
||||
import http from 'http';
|
||||
|
||||
// The first scheduler connection can outlive its short RPC deadline. Let the
|
||||
// normal single-flight recovery finish within the supervised startup budget.
|
||||
async function waitForUpgradeScheduler(
|
||||
readiness: { recover(): Promise<boolean> },
|
||||
readiness: {
|
||||
recover(): Promise<boolean>;
|
||||
},
|
||||
timeoutMs: number,
|
||||
retryMs = 250,
|
||||
) {
|
||||
@@ -22,13 +23,12 @@ async function waitForUpgradeScheduler(
|
||||
} while (Date.now() < deadline);
|
||||
throw new Error('Upgrade scheduler readiness failed');
|
||||
}
|
||||
|
||||
async function probeUpgrade() {
|
||||
if (!process.send || process.env.QL_UPGRADE_PROBE !== '1')
|
||||
throw new Error('Upgrade probe requires its isolated supervisor');
|
||||
dns.setDefaultResultOrder('ipv4first');
|
||||
const { default: config } = await import('../config');
|
||||
const { sequelize } = await import('../data');
|
||||
const { database } = await import('../data');
|
||||
const { default: loadDatabase } = await import('../loaders/db');
|
||||
const { Container } = await import('typedi');
|
||||
const { GrpcServerService } = await import('../services/grpc');
|
||||
@@ -43,17 +43,17 @@ async function probeUpgrade() {
|
||||
try {
|
||||
await loadDatabase();
|
||||
// Exercise an actual on-disk transaction as well as schema initialization.
|
||||
await sequelize.transaction(async (transaction) => {
|
||||
await sequelize.query('CREATE TABLE upgrade_probe (value INTEGER)', {
|
||||
transaction,
|
||||
});
|
||||
await sequelize.query('INSERT INTO upgrade_probe VALUES (42)', {
|
||||
transaction,
|
||||
});
|
||||
const [rows] = await sequelize.query('SELECT value FROM upgrade_probe', {
|
||||
transaction,
|
||||
});
|
||||
if ((rows[0] as { value: number })?.value !== 42)
|
||||
await database.transaction(async () => {
|
||||
await database.query('CREATE TABLE upgrade_probe (value INTEGER)');
|
||||
await database.query('INSERT INTO upgrade_probe VALUES (42)');
|
||||
const rows = await database.query('SELECT value FROM upgrade_probe');
|
||||
if (
|
||||
(
|
||||
rows[0] as {
|
||||
value: number;
|
||||
}
|
||||
)?.value !== 42
|
||||
)
|
||||
throw new Error('Upgrade database readback failed');
|
||||
});
|
||||
inject();
|
||||
@@ -64,8 +64,11 @@ async function probeUpgrade() {
|
||||
cronClient.readiness,
|
||||
process.arch === 'arm' &&
|
||||
Number(
|
||||
(process.config.variables as { arm_version?: string | number })
|
||||
.arm_version,
|
||||
(
|
||||
process.config.variables as {
|
||||
arm_version?: string | number;
|
||||
}
|
||||
).arm_version,
|
||||
) === 6
|
||||
? 60000
|
||||
: 10000,
|
||||
@@ -119,10 +122,9 @@ async function probeUpgrade() {
|
||||
} finally {
|
||||
await server.shutdown();
|
||||
grpc.getServer().forceShutdown();
|
||||
await sequelize.close();
|
||||
await database.close();
|
||||
}
|
||||
}
|
||||
|
||||
process.once('disconnect', () => process.exit(1));
|
||||
probeUpgrade()
|
||||
.then(() => process.exit(0))
|
||||
|
||||
@@ -180,10 +180,12 @@ export default {
|
||||
'/api/user/two-factor/login',
|
||||
'/api/system',
|
||||
'/api/user/init',
|
||||
'/api/user/notification/init',
|
||||
'/open/user/login',
|
||||
'/open/user/two-factor/login',
|
||||
'/open/system',
|
||||
'/open/user/init',
|
||||
'/open/user/notification/init',
|
||||
],
|
||||
versionFile,
|
||||
lastVersionFile,
|
||||
|
||||
+16
-60
@@ -1,5 +1,3 @@
|
||||
import { cronOperand } from '../shared/cronOperand';
|
||||
import { finishStoppedTree, isProcessDescendant, systemOwner } from '../shared/cronProcess';
|
||||
import * as fs from 'fs/promises';
|
||||
import { statSync } from 'fs';
|
||||
import * as path from 'path';
|
||||
@@ -8,7 +6,7 @@ import psTreeFun from 'ps-tree';
|
||||
import { promisify } from 'util';
|
||||
import { load } from 'js-yaml';
|
||||
import config from './index';
|
||||
import { PYTHON_INSTALL_DIR, PYTHON_VENV_DIR } from './const';
|
||||
import { PYTHON_INSTALL_DIR, PYTHON_VENV_DIR, TASK_COMMAND } from './const';
|
||||
import Logger from '../loaders/logger';
|
||||
import { writeFileWithLock } from '../shared/utils';
|
||||
import { DependenceTypes } from '../data/dependence';
|
||||
@@ -498,17 +496,13 @@ export function psTree(pid: number): Promise<number[]> {
|
||||
});
|
||||
}
|
||||
|
||||
export async function killTask(pid: number, waitForExit = false, verifyOwner?: () => void,
|
||||
withStopRequest?: (signalTree: () => Error | void, targets: string[]) => Promise<void | { targets: string[]; signalledAt: number | null }>) {
|
||||
export async function killTask(pid: number, waitForExit = false) {
|
||||
const descendants = await psTree(pid);
|
||||
verifyOwner?.();
|
||||
const signal = (target: number, sig: NodeJS.Signals) => {
|
||||
try {
|
||||
process.kill(target, sig);
|
||||
return true;
|
||||
} catch (error: any) {
|
||||
if (error.code !== 'ESRCH') throw error;
|
||||
return false;
|
||||
}
|
||||
};
|
||||
if (!waitForExit) {
|
||||
@@ -521,53 +515,8 @@ export async function killTask(pid: number, waitForExit = false, verifyOwner?: (
|
||||
return;
|
||||
}
|
||||
const pids = [...descendants.reverse(), pid];
|
||||
const births = new Map<number, string>();
|
||||
if (verifyOwner) {
|
||||
for (const target of pids) {
|
||||
try {
|
||||
const birth = systemOwner(target);
|
||||
if (target === pid || isProcessDescendant(target, pid)) births.set(target, birth);
|
||||
} catch (error) {
|
||||
if (!['ENOENT', 'ESRCH'].includes((error as NodeJS.ErrnoException).code!)) throw error;
|
||||
}
|
||||
}
|
||||
verifyOwner();
|
||||
}
|
||||
const sameProcess = (target: number) => {
|
||||
if (!verifyOwner) return true;
|
||||
if (!births.has(target)) return false;
|
||||
try { return births.get(target) === systemOwner(target); }
|
||||
catch (error) {
|
||||
if (['ENOENT', 'ESRCH'].includes((error as NodeJS.ErrnoException).code!)) return false;
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
const signalTree = () => {
|
||||
verifyOwner?.();
|
||||
// The root owns the command's result. An ESRCH here must roll back the
|
||||
// stop claim even if a descendant is still draining the output pipe.
|
||||
if (verifyOwner && (!sameProcess(pid) || !signal(pid, 'SIGTERM'))) {
|
||||
throw Object.assign(new Error('Command already exited'), { code: 'ESRCH' });
|
||||
}
|
||||
let deliveryError: Error | undefined;
|
||||
for (const target of pids) {
|
||||
if (verifyOwner && target === pid) continue;
|
||||
try {
|
||||
if (sameProcess(target)) signal(target, 'SIGTERM');
|
||||
} catch (error) {
|
||||
if (!withStopRequest || !verifyOwner) throw error;
|
||||
// Root TERM succeeded. Commit that fact even if a child needs a retry.
|
||||
deliveryError ??= error as Error;
|
||||
}
|
||||
}
|
||||
return deliveryError;
|
||||
};
|
||||
if (withStopRequest) {
|
||||
const claim = await withStopRequest(signalTree, [...births.values()]);
|
||||
if (claim) return finishStoppedTree(claim.targets, claim.signalledAt);
|
||||
} else signalTree();
|
||||
for (const target of pids) signal(target, 'SIGTERM');
|
||||
const alive = async (target: number) => {
|
||||
if (!sameProcess(target)) return false;
|
||||
try {
|
||||
process.kill(target, 0);
|
||||
} catch (error: any) {
|
||||
@@ -606,9 +555,7 @@ export async function killTask(pid: number, waitForExit = false, verifyOwner?: (
|
||||
};
|
||||
let remaining = await wait();
|
||||
if (!remaining.length) return;
|
||||
for (const target of remaining) {
|
||||
if (sameProcess(target)) signal(target, 'SIGKILL');
|
||||
}
|
||||
for (const target of remaining) signal(target, 'SIGKILL');
|
||||
remaining = await wait();
|
||||
if (remaining.length)
|
||||
throw new Error(`Task processes did not exit: ${remaining.join(', ')}`);
|
||||
@@ -665,7 +612,17 @@ export async function getUniqPath(
|
||||
suffix = `_${id}`;
|
||||
}
|
||||
|
||||
let str = cronOperand(command) || 'task';
|
||||
let items = command.split(/ +/);
|
||||
|
||||
const maxTimeCommandIndex = items.findIndex((x) => x === '-m');
|
||||
if (maxTimeCommandIndex !== -1) {
|
||||
items = items.slice(maxTimeCommandIndex + 2);
|
||||
}
|
||||
|
||||
let str = items[0];
|
||||
if (items[0] === TASK_COMMAND) {
|
||||
str = items[1];
|
||||
}
|
||||
|
||||
const dotIndex = str.lastIndexOf('.');
|
||||
|
||||
@@ -685,8 +642,7 @@ export async function getUniqPath(
|
||||
str = `${tempStr}_${str.slice(slashIndex + 1)}`;
|
||||
}
|
||||
|
||||
const base = str.replace(/[^a-zA-Z0-9_\u4e00-\u9fa5.-]+/g, '_').slice(0, 100 - suffix.length);
|
||||
return `${base && !/^\.+$/.test(base) ? base : 'task'}${suffix}`;
|
||||
return `${str}${suffix}`;
|
||||
}
|
||||
|
||||
export function safeJSONParse(value?: string) {
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
import { EventEmitter } from 'events';
|
||||
import { database } from '.';
|
||||
import { DatabaseClient } from './databaseClient';
|
||||
|
||||
// Keep the existing Keyv serialization and namespace. Only its SQLite transport
|
||||
// changes; old cached authentication records remain readable in either version.
|
||||
export class CacheStore extends EventEmitter {
|
||||
readonly opts = { dialect: 'sqlite' };
|
||||
namespace?: string;
|
||||
constructor(private client: () => DatabaseClient = () => database) {
|
||||
super();
|
||||
}
|
||||
get(key: string): Promise<string | undefined> {
|
||||
return this.client().request('cache', 'get', key);
|
||||
}
|
||||
async set(key: string, value: string) {
|
||||
return this.client().request('cache', 'set', key, value);
|
||||
}
|
||||
async delete(key: string): Promise<boolean> {
|
||||
return this.client().request('cache', 'delete', key);
|
||||
}
|
||||
async clear(): Promise<void> {
|
||||
throw new Error('Clearing all authentication namespaces is not supported');
|
||||
}
|
||||
async disconnect(): Promise<void> {
|
||||
/* The shared database client owns the worker. */
|
||||
}
|
||||
}
|
||||
+4
-51
@@ -1,5 +1,4 @@
|
||||
import { sequelize } from '.';
|
||||
import { DataTypes, Model, ModelDefined } from 'sequelize';
|
||||
import { Repository, RecordRow } from './repository';
|
||||
|
||||
export class Crontab {
|
||||
name?: string;
|
||||
@@ -16,8 +15,7 @@ export class Crontab {
|
||||
queued_token?: string | null;
|
||||
isPinned?: 1 | 0;
|
||||
labels?: string[];
|
||||
last_instance_id?: number;
|
||||
last_running_time?: number | null;
|
||||
last_running_time?: number;
|
||||
last_execution_time?: number;
|
||||
sub_id?: number;
|
||||
extra_schedules?: Array<{ schedule: string }>;
|
||||
@@ -25,10 +23,6 @@ export class Crontab {
|
||||
task_after?: string;
|
||||
log_name?: string;
|
||||
allow_multiple_instances?: 1 | 0;
|
||||
skip_if_pending?: boolean;
|
||||
max_queue_wait?: number;
|
||||
catchup_seconds?: number;
|
||||
recovery_from?: number;
|
||||
work_dir?: string;
|
||||
|
||||
constructor(options: Crontab) {
|
||||
@@ -56,10 +50,6 @@ export class Crontab {
|
||||
this.task_after = options.task_after;
|
||||
this.log_name = options.log_name;
|
||||
this.allow_multiple_instances = options.allow_multiple_instances || 0;
|
||||
this.skip_if_pending = Boolean(options.skip_if_pending);
|
||||
this.max_queue_wait = options.max_queue_wait || 0;
|
||||
this.catchup_seconds = options.catchup_seconds || 0;
|
||||
this.recovery_from = options.recovery_from;
|
||||
this.work_dir = options.work_dir;
|
||||
}
|
||||
}
|
||||
@@ -71,42 +61,5 @@ export enum CrontabStatus {
|
||||
'queued' = 3,
|
||||
}
|
||||
|
||||
export interface CronInstance extends Model<Crontab, Crontab>, Crontab {}
|
||||
export const CrontabModel = sequelize.define<CronInstance>('Crontab', {
|
||||
name: {
|
||||
unique: 'compositeIndex',
|
||||
type: DataTypes.STRING,
|
||||
},
|
||||
command: {
|
||||
unique: 'compositeIndex',
|
||||
type: DataTypes.STRING,
|
||||
},
|
||||
schedule: {
|
||||
unique: 'compositeIndex',
|
||||
type: DataTypes.STRING,
|
||||
},
|
||||
timestamp: DataTypes.STRING,
|
||||
saved: DataTypes.BOOLEAN,
|
||||
status: DataTypes.NUMBER,
|
||||
isSystem: DataTypes.NUMBER,
|
||||
pid: DataTypes.NUMBER,
|
||||
isDisabled: DataTypes.NUMBER,
|
||||
isPinned: DataTypes.NUMBER,
|
||||
log_path: DataTypes.STRING,
|
||||
queued_token: DataTypes.STRING,
|
||||
labels: DataTypes.JSON,
|
||||
last_instance_id: DataTypes.INTEGER,
|
||||
last_running_time: DataTypes.NUMBER,
|
||||
last_execution_time: DataTypes.NUMBER,
|
||||
sub_id: { type: DataTypes.NUMBER, allowNull: true },
|
||||
extra_schedules: DataTypes.JSON,
|
||||
task_before: DataTypes.STRING,
|
||||
task_after: DataTypes.STRING,
|
||||
log_name: DataTypes.STRING,
|
||||
allow_multiple_instances: DataTypes.NUMBER,
|
||||
skip_if_pending: DataTypes.BOOLEAN,
|
||||
max_queue_wait: DataTypes.INTEGER,
|
||||
catchup_seconds: DataTypes.INTEGER,
|
||||
recovery_from: DataTypes.BIGINT,
|
||||
work_dir: DataTypes.STRING,
|
||||
});
|
||||
export type CronInstance = RecordRow<Crontab>;
|
||||
export const CrontabModel = new Repository<Crontab>('Crontab');
|
||||
|
||||
+3
-57
@@ -1,5 +1,4 @@
|
||||
import { DataTypes, Model } from 'sequelize';
|
||||
import { sequelize } from '.';
|
||||
import { Repository, RecordRow } from './repository';
|
||||
|
||||
export class CrontabStat {
|
||||
id?: number;
|
||||
@@ -8,10 +7,8 @@ export class CrontabStat {
|
||||
run_count?: number;
|
||||
success_count?: number;
|
||||
fail_count?: number;
|
||||
untimed_count?: number;
|
||||
total_time?: number;
|
||||
max_time?: number;
|
||||
fixed_max_time?: number | null;
|
||||
|
||||
constructor(options: CrontabStat) {
|
||||
this.id = options.id;
|
||||
@@ -20,61 +17,10 @@ export class CrontabStat {
|
||||
this.run_count = options.run_count || 0;
|
||||
this.success_count = options.success_count || 0;
|
||||
this.fail_count = options.fail_count || 0;
|
||||
this.untimed_count = options.untimed_count || 0;
|
||||
this.total_time = options.total_time || 0;
|
||||
this.max_time = options.max_time || 0;
|
||||
}
|
||||
}
|
||||
|
||||
export interface CrontabStatInstance extends Model<CrontabStat, CrontabStat>, CrontabStat {}
|
||||
|
||||
export const CrontabStatModel = sequelize.define<CrontabStatInstance>(
|
||||
'CrontabStat',
|
||||
{
|
||||
id: {
|
||||
type: DataTypes.INTEGER,
|
||||
primaryKey: true,
|
||||
autoIncrement: true,
|
||||
},
|
||||
ref_id: {
|
||||
type: DataTypes.NUMBER,
|
||||
allowNull: false,
|
||||
},
|
||||
date: {
|
||||
type: DataTypes.STRING,
|
||||
allowNull: false,
|
||||
},
|
||||
run_count: {
|
||||
type: DataTypes.NUMBER,
|
||||
defaultValue: 0,
|
||||
},
|
||||
success_count: {
|
||||
type: DataTypes.NUMBER,
|
||||
defaultValue: 0,
|
||||
},
|
||||
fail_count: {
|
||||
type: DataTypes.NUMBER,
|
||||
defaultValue: 0,
|
||||
},
|
||||
untimed_count: {
|
||||
type: DataTypes.INTEGER,
|
||||
allowNull: false,
|
||||
defaultValue: 0,
|
||||
},
|
||||
total_time: {
|
||||
type: DataTypes.NUMBER,
|
||||
defaultValue: 0,
|
||||
},
|
||||
fixed_max_time: { type: DataTypes.NUMBER, allowNull: true },
|
||||
max_time: {
|
||||
type: DataTypes.NUMBER,
|
||||
defaultValue: 0,
|
||||
},
|
||||
},
|
||||
{
|
||||
indexes: [
|
||||
{ unique: true, fields: ['ref_id', 'date'] },
|
||||
{ fields: ['date'] },
|
||||
],
|
||||
},
|
||||
);
|
||||
export type CrontabStatInstance = RecordRow<CrontabStat>;
|
||||
export const CrontabStatModel = new Repository<CrontabStat>('CrontabStat');
|
||||
|
||||
+3
-23
@@ -1,5 +1,4 @@
|
||||
import { sequelize } from '.';
|
||||
import { DataTypes, Model } from 'sequelize';
|
||||
import { Repository, RecordRow } from './repository';
|
||||
|
||||
export enum CronViewType {
|
||||
'系统' = 1,
|
||||
@@ -39,24 +38,5 @@ export class CrontabView {
|
||||
}
|
||||
}
|
||||
|
||||
export interface CronViewInstance
|
||||
extends Model<CrontabView, CrontabView>,
|
||||
CrontabView {}
|
||||
export const CrontabViewModel = sequelize.define<CronViewInstance>(
|
||||
'CrontabView',
|
||||
{
|
||||
name: {
|
||||
unique: 'name',
|
||||
type: DataTypes.STRING,
|
||||
},
|
||||
position: DataTypes.NUMBER,
|
||||
isDisabled: DataTypes.NUMBER,
|
||||
filters: DataTypes.JSON,
|
||||
sorts: DataTypes.JSON,
|
||||
filterRelation: {
|
||||
type: DataTypes.STRING,
|
||||
allowNull: true,
|
||||
},
|
||||
type: DataTypes.NUMBER,
|
||||
},
|
||||
);
|
||||
export type CronViewInstance = RecordRow<CrontabView>;
|
||||
export const CrontabViewModel = new Repository<CrontabView>('CrontabView');
|
||||
|
||||
@@ -0,0 +1,325 @@
|
||||
import { AsyncLocalStorage } from 'async_hooks';
|
||||
import { ChildProcess, fork } from 'child_process';
|
||||
import { join } from 'path';
|
||||
import { setTimeout, clearTimeout } from 'timers';
|
||||
import { DatabaseError } from './databaseErrors';
|
||||
|
||||
type Scope = { active: boolean; child: boolean; token: number };
|
||||
type Reply = {
|
||||
id: number;
|
||||
value?: any;
|
||||
error?: { code: string; message: string };
|
||||
};
|
||||
type Limits = { timeoutMs?: number; queueLimit?: number };
|
||||
|
||||
// One worker per backend process; SQLite itself coordinates independent processes.
|
||||
// A transaction owns this client's queue until its callback and commit finish.
|
||||
export class DatabaseClient {
|
||||
private worker?: ChildProcess;
|
||||
private stopped: Promise<void> = Promise.resolve();
|
||||
private failed?: Error;
|
||||
private closed = false;
|
||||
private nextId = 0;
|
||||
private queued = 0;
|
||||
private tail: Promise<void> = Promise.resolve();
|
||||
private pending = new Map<
|
||||
number,
|
||||
{
|
||||
resolve(value: any): void;
|
||||
reject(error: Error): void;
|
||||
timer: NodeJS.Timeout;
|
||||
}
|
||||
>();
|
||||
private scope = new AsyncLocalStorage<Scope>();
|
||||
|
||||
private readonly timeoutMs: number;
|
||||
private readonly queueLimit: number;
|
||||
|
||||
constructor(
|
||||
public readonly storage: string,
|
||||
private cacheStorage?: string,
|
||||
limits: Limits = {},
|
||||
) {
|
||||
this.timeoutMs =
|
||||
limits.timeoutMs ?? (process.arch === 'arm' ? 300000 : 60000);
|
||||
this.queueLimit = limits.queueLimit ?? 256;
|
||||
if (
|
||||
!Number.isSafeInteger(this.timeoutMs) ||
|
||||
this.timeoutMs < 1 ||
|
||||
!Number.isSafeInteger(this.queueLimit) ||
|
||||
this.queueLimit < 1
|
||||
)
|
||||
throw new Error('Invalid database worker limits');
|
||||
}
|
||||
|
||||
private abort(error: Error) {
|
||||
this.failed ||= error;
|
||||
for (const request of this.pending.values()) {
|
||||
clearTimeout(request.timer);
|
||||
request.reject(this.failed);
|
||||
}
|
||||
this.pending.clear();
|
||||
this.unref();
|
||||
this.worker?.kill('SIGKILL');
|
||||
}
|
||||
|
||||
private unref() {
|
||||
this.worker?.unref();
|
||||
this.worker?.channel?.unref();
|
||||
}
|
||||
|
||||
private start() {
|
||||
if (this.worker) return this.worker;
|
||||
const [major, minor] = process.versions.node.split('.').map(Number);
|
||||
if (major < 22 || (major === 22 && minor < 17))
|
||||
throw new DatabaseError(
|
||||
'Qinglong requires Node >=22.17; keep the previous installation until Node is upgraded',
|
||||
'UNSUPPORTED_NODE',
|
||||
);
|
||||
// ts-node's CLI places its executable in execArgv, rather than using -r.
|
||||
// Source workers register their own compiler; compiled workers need none.
|
||||
const preloads = __filename.endsWith('.ts')
|
||||
? ['--require', require.resolve('ts-node/register/transpile-only')]
|
||||
: [];
|
||||
const armv6 =
|
||||
process.arch === 'arm' &&
|
||||
Number(
|
||||
(process.config.variables as { arm_version?: string | number })
|
||||
.arm_version,
|
||||
) === 6;
|
||||
const worker = fork(require.resolve('./databaseProcess'), [], {
|
||||
serialization: 'advanced',
|
||||
stdio: ['ignore', 'ignore', 'ignore', 'ipc'],
|
||||
execArgv: [
|
||||
...preloads,
|
||||
...(armv6 ? ['--jitless'] : []),
|
||||
'--max-old-space-size=128',
|
||||
],
|
||||
env: {
|
||||
...process.env,
|
||||
NODE_OPTIONS: '',
|
||||
...(__filename.endsWith('.ts')
|
||||
? { TS_NODE_PROJECT: join(__dirname, 'tsconfig.worker.json') }
|
||||
: {}),
|
||||
},
|
||||
});
|
||||
this.stopped = new Promise((resolve) =>
|
||||
worker.once('close', () => resolve()),
|
||||
);
|
||||
const onOwnerExit = () => worker.kill('SIGKILL');
|
||||
process.once('exit', onOwnerExit);
|
||||
worker.once('close', () => process.removeListener('exit', onOwnerExit));
|
||||
this.worker = worker;
|
||||
worker.on('message', (reply: Reply & { type?: string }) => {
|
||||
if (reply.type === 'fatal' && reply.error) {
|
||||
this.abort(new DatabaseError(reply.error.message, reply.error.code));
|
||||
return;
|
||||
}
|
||||
const request = this.pending.get(reply.id);
|
||||
if (!request) return;
|
||||
this.pending.delete(reply.id);
|
||||
clearTimeout(request.timer);
|
||||
if (!this.pending.size) this.unref();
|
||||
if (reply.error)
|
||||
request.reject(
|
||||
new DatabaseError(reply.error.message, reply.error.code),
|
||||
);
|
||||
else request.resolve(reply.value);
|
||||
});
|
||||
const fail = () =>
|
||||
this.abort(
|
||||
new DatabaseError(
|
||||
'Database worker stopped; restart the service before retrying a write',
|
||||
'DATABASE_WORKER_EXIT',
|
||||
),
|
||||
);
|
||||
worker.on('error', fail);
|
||||
worker.on('exit', () => {
|
||||
if (!this.closed) fail();
|
||||
});
|
||||
worker.send({
|
||||
storage: this.storage,
|
||||
cacheStorage: this.cacheStorage,
|
||||
ownerPid: process.pid,
|
||||
});
|
||||
this.unref();
|
||||
return worker;
|
||||
}
|
||||
|
||||
private send(
|
||||
operation: string,
|
||||
args: any[] = [],
|
||||
token?: number,
|
||||
): Promise<any> {
|
||||
if (this.failed) return Promise.reject(this.failed);
|
||||
if (this.closed)
|
||||
return Promise.reject(
|
||||
new DatabaseError('Database is closed', 'DATABASE_CLOSED'),
|
||||
);
|
||||
return new Promise((resolve, reject) => {
|
||||
try {
|
||||
const worker = this.start();
|
||||
const id = ++this.nextId;
|
||||
const timer = setTimeout(
|
||||
() =>
|
||||
this.abort(
|
||||
new DatabaseError(
|
||||
'Database worker timed out; writes are never automatically replayed',
|
||||
'DATABASE_WORKER_TIMEOUT',
|
||||
),
|
||||
),
|
||||
this.timeoutMs,
|
||||
);
|
||||
timer.unref();
|
||||
this.pending.set(id, { resolve, reject, timer });
|
||||
worker.ref();
|
||||
worker.channel?.ref();
|
||||
try {
|
||||
worker.send({ id, operation, args, token }, (error) => {
|
||||
if (error)
|
||||
this.abort(
|
||||
new DatabaseError(
|
||||
'Database IPC disconnected',
|
||||
'DATABASE_WORKER_EXIT',
|
||||
),
|
||||
);
|
||||
});
|
||||
} catch (error) {
|
||||
this.pending.delete(id);
|
||||
clearTimeout(timer);
|
||||
if (!this.pending.size) this.unref();
|
||||
reject(error);
|
||||
}
|
||||
} catch (error) {
|
||||
reject(error);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private exclusive<T>(
|
||||
operation: () => Promise<T>,
|
||||
shutdown = false,
|
||||
): Promise<T> {
|
||||
if (!shutdown && this.queued >= this.queueLimit)
|
||||
return Promise.reject(
|
||||
new DatabaseError('Database request queue is full', 'DATABASE_BUSY'),
|
||||
);
|
||||
this.queued++;
|
||||
const previous = this.tail;
|
||||
let release!: () => void;
|
||||
this.tail = new Promise<void>((resolve) => {
|
||||
release = resolve;
|
||||
});
|
||||
return previous.then(operation).finally(() => {
|
||||
this.queued--;
|
||||
release();
|
||||
});
|
||||
}
|
||||
|
||||
request<T = any>(operation: string, ...args: any[]): Promise<T> {
|
||||
const scope = this.scope.getStore();
|
||||
if (scope) {
|
||||
if (!scope.active || scope.child)
|
||||
return Promise.reject(
|
||||
new DatabaseError(
|
||||
'Transaction scope is no longer available',
|
||||
'TRANSACTION_SCOPE',
|
||||
),
|
||||
);
|
||||
if (this.pending.size >= this.queueLimit)
|
||||
return Promise.reject(
|
||||
new DatabaseError('Database request queue is full', 'DATABASE_BUSY'),
|
||||
);
|
||||
return this.send(operation, args, scope.token);
|
||||
}
|
||||
return this.exclusive(() => this.send(operation, args));
|
||||
}
|
||||
|
||||
async transaction<T>(operation: () => Promise<T>): Promise<T> {
|
||||
const parent = this.scope.getStore();
|
||||
if (parent && (!parent.active || parent.child))
|
||||
throw new DatabaseError(
|
||||
'Concurrent or expired nested transaction',
|
||||
'TRANSACTION_SCOPE',
|
||||
);
|
||||
const run = async () => {
|
||||
const token = ++this.nextId;
|
||||
if (parent) parent.child = true;
|
||||
const scope: Scope = { active: true, child: false, token };
|
||||
let began = false;
|
||||
let timer: NodeJS.Timeout | undefined;
|
||||
try {
|
||||
await this.send('begin', [], token);
|
||||
began = true;
|
||||
const deadline = new Promise<never>((_, reject) => {
|
||||
timer = setTimeout(
|
||||
() =>
|
||||
reject(
|
||||
new DatabaseError(
|
||||
'Database transaction timed out',
|
||||
'DATABASE_TRANSACTION_TIMEOUT',
|
||||
),
|
||||
),
|
||||
this.timeoutMs,
|
||||
);
|
||||
});
|
||||
const value = await Promise.race([
|
||||
this.scope.run(scope, operation),
|
||||
deadline,
|
||||
]);
|
||||
scope.active = false;
|
||||
await this.send('commit', [], token);
|
||||
return value;
|
||||
} catch (error) {
|
||||
scope.active = false;
|
||||
if (began) {
|
||||
try {
|
||||
await this.send('rollback', [], token);
|
||||
} catch {
|
||||
this.abort(
|
||||
new DatabaseError(
|
||||
'Transaction rollback failed; restart the service',
|
||||
'DATABASE_ROLLBACK_FAILED',
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
throw error;
|
||||
} finally {
|
||||
clearTimeout(timer);
|
||||
if (parent) parent.child = false;
|
||||
}
|
||||
};
|
||||
return parent ? run() : this.exclusive(run);
|
||||
}
|
||||
|
||||
query<T = Record<string, unknown>>(
|
||||
sql: string,
|
||||
params: unknown[] = [],
|
||||
): Promise<T[]> {
|
||||
return this.request('query', sql, params);
|
||||
}
|
||||
|
||||
get healthy() {
|
||||
return !this.failed && !this.closed;
|
||||
}
|
||||
|
||||
async close() {
|
||||
if (this.scope.getStore())
|
||||
throw new DatabaseError(
|
||||
'Cannot close within a transaction',
|
||||
'TRANSACTION_SCOPE',
|
||||
);
|
||||
await this.exclusive(async () => {
|
||||
if (this.closed) return;
|
||||
try {
|
||||
if (this.worker && !this.failed) await this.send('close');
|
||||
} finally {
|
||||
this.closed = true;
|
||||
this.worker?.ref();
|
||||
this.worker?.kill('SIGKILL');
|
||||
await this.stopped;
|
||||
}
|
||||
}, true);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
// Error details (SQL, bindings, credentials) stay inside the database worker.
|
||||
export class DatabaseError extends Error {
|
||||
constructor(message: string, public readonly code: string) {
|
||||
super(message);
|
||||
this.name = 'DatabaseError';
|
||||
}
|
||||
}
|
||||
|
||||
export function databaseStartupFailure(value: unknown) {
|
||||
const error = (value && typeof value === 'object' ? value : {}) as Error & { code?: string };
|
||||
const missing = /Cannot find (?:module|package) ['"]([^'"]+)['"]/.exec(
|
||||
error.message || '',
|
||||
)?.[1];
|
||||
const importer = /Require stack:\r?\n-\s+([^\r\n]+)/.exec(
|
||||
error.message || '',
|
||||
)?.[1];
|
||||
const dependency =
|
||||
/MODULE_NOT_FOUND/.test(error.code || '') &&
|
||||
Boolean(
|
||||
missing &&
|
||||
((!missing.startsWith('.') &&
|
||||
!missing.startsWith('/') &&
|
||||
!missing.startsWith('node:')) ||
|
||||
/node_modules[/\\]/.test(missing) ||
|
||||
/node_modules[/\\]/.test(importer || '')),
|
||||
);
|
||||
return dependency
|
||||
? {
|
||||
code: 'MODULE_NOT_FOUND',
|
||||
message: "Cannot find module '@mikro-orm/sql'",
|
||||
}
|
||||
: {
|
||||
code: 'DATABASE_WORKER_EXIT',
|
||||
message: 'Database process failed to start',
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
import { databaseStartupFailure } from './databaseErrors';
|
||||
import { Worker } from 'worker_threads';
|
||||
|
||||
// IPC disconnect cannot run while DatabaseSync is executing SQL. Start this
|
||||
// independent, allocation-light monitor before opening SQLite so a SIGKILLed
|
||||
// backend cannot leave an orphan holding the old service's database write lock.
|
||||
async function monitorOwner(ownerPid: number) {
|
||||
if (!Number.isSafeInteger(ownerPid) || ownerPid < 1)
|
||||
throw new Error('Invalid database owner');
|
||||
const monitor = new Worker(
|
||||
`
|
||||
const {parentPort,workerData}=require('node:worker_threads');
|
||||
process.on('uncaughtException',()=>process.kill(process.pid,'SIGKILL'));
|
||||
const check=()=>{
|
||||
if(process.ppid!==workerData.ownerPid)process.kill(process.pid,'SIGKILL');
|
||||
};
|
||||
check();
|
||||
setInterval(check,500);
|
||||
parentPort.postMessage('ready');
|
||||
`,
|
||||
{
|
||||
eval: true,
|
||||
workerData: { ownerPid },
|
||||
// V8's process-wide --jitless remains active on ARMv6. Do not load the
|
||||
// source worker's ts-node compiler into this tiny, plain-JavaScript monitor.
|
||||
execArgv: [],
|
||||
resourceLimits: {
|
||||
maxOldGenerationSizeMb: 8,
|
||||
maxYoungGenerationSizeMb: 2,
|
||||
stackSizeMb: 1,
|
||||
},
|
||||
},
|
||||
);
|
||||
monitor.once('exit', () => process.exit(1));
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
monitor.once('message', () => resolve());
|
||||
monitor.once('error', reject);
|
||||
});
|
||||
monitor.unref();
|
||||
}
|
||||
|
||||
// The bootstrap catches dependency import errors before the ORM module loads.
|
||||
// The advanced IPC serializer preserves Date, Buffer and undefined values.
|
||||
process.once('disconnect', () => process.exit(1));
|
||||
process.once('message', async (settings) => {
|
||||
const pending: unknown[] = [];
|
||||
const buffer = (request: unknown) => pending.push(request);
|
||||
// Keep a listener throughout asynchronous monitor startup. Node may flush
|
||||
// several buffered IPC messages while delivering the initial settings.
|
||||
process.on('message', buffer);
|
||||
try {
|
||||
await monitorOwner((settings as { ownerPid: number }).ownerPid);
|
||||
require('./databaseWorker').startDatabaseWorker(settings);
|
||||
process.removeListener('message', buffer);
|
||||
for (const request of pending) process.emit('message', request, undefined);
|
||||
} catch (error) {
|
||||
process.send?.({ type: 'fatal', error: databaseStartupFailure(error) });
|
||||
} finally {
|
||||
process.removeListener('message', buffer);
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,280 @@
|
||||
import { mkdirSync } from 'fs';
|
||||
import { dirname } from 'path';
|
||||
import { EntitySchema, Type } from '@mikro-orm/core';
|
||||
import { MikroORM, SqliteDriver, NodeSqliteDialect, raw } from '@mikro-orm/sql';
|
||||
import { entityDefinitions } from './schema';
|
||||
|
||||
// Sequelize DATE readers expect TEXT. Numeric epoch dates would break rollback.
|
||||
class LegacyDateType extends Type<Date, string> {
|
||||
convertToDatabaseValue(value: Date) {
|
||||
return value == null
|
||||
? value
|
||||
: value.toISOString().replace('T', ' ').replace('Z', ' +00:00');
|
||||
}
|
||||
convertToJSValue(value: string | Date) {
|
||||
return value == null
|
||||
? value
|
||||
: value instanceof Date
|
||||
? value
|
||||
: new Date(value);
|
||||
}
|
||||
getColumnType() {
|
||||
return 'DATETIME';
|
||||
}
|
||||
compareAsType() {
|
||||
return 'string' as const;
|
||||
}
|
||||
get runtimeType() {
|
||||
return 'Date';
|
||||
}
|
||||
}
|
||||
|
||||
const entities = Object.values(entityDefinitions).map(
|
||||
(definition) =>
|
||||
new EntitySchema({
|
||||
...definition,
|
||||
properties: Object.fromEntries(
|
||||
Object.entries(definition.properties).map(([name, field]) => [
|
||||
name,
|
||||
{
|
||||
...field,
|
||||
type:
|
||||
field.type === 'legacyDate' ? new LegacyDateType() : field.type,
|
||||
},
|
||||
]),
|
||||
),
|
||||
} as any),
|
||||
);
|
||||
let orm: Awaited<ReturnType<typeof MikroORM.init<SqliteDriver>>>;
|
||||
let cache: any;
|
||||
const transactions: number[] = [];
|
||||
let ready: Promise<void>;
|
||||
let workerData: { storage: string; cacheStorage?: string; ownerPid: number };
|
||||
|
||||
async function initialize() {
|
||||
if (workerData.storage !== ':memory:')
|
||||
mkdirSync(dirname(workerData.storage), { recursive: true });
|
||||
orm = await MikroORM.init<SqliteDriver>({
|
||||
driver: SqliteDriver,
|
||||
driverOptions: new NodeSqliteDialect(workerData.storage),
|
||||
dbName: workerData.storage,
|
||||
entities,
|
||||
debug: false,
|
||||
allowGlobalContext: false,
|
||||
discovery: { warnWhenNoEntities: false },
|
||||
});
|
||||
await orm.em.getConnection().execute('PRAGMA busy_timeout=10000');
|
||||
}
|
||||
|
||||
function filter(name: keyof typeof entityDefinitions, value: any): any {
|
||||
if (value === undefined) throw new Error('Undefined database predicate');
|
||||
if (value == null || typeof value !== 'object' || value instanceof Date)
|
||||
return value;
|
||||
if (Array.isArray(value)) return value.map((part) => filter(name, part));
|
||||
const properties = entityDefinitions[name].properties;
|
||||
return Object.fromEntries(
|
||||
Object.entries(value).map(([key, item]: [string, any]) => {
|
||||
if (item === undefined) throw new Error('Undefined database predicate');
|
||||
// LIKE searches JSON's serialized text, matching the pre-migration behavior.
|
||||
if (
|
||||
key in properties &&
|
||||
(properties as any)[key].type === 'json' &&
|
||||
item &&
|
||||
typeof item === 'object' &&
|
||||
'$like' in item
|
||||
)
|
||||
return [raw(`cast("${key}" as text)`), item];
|
||||
return [key, filter(name, item)];
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
function values(
|
||||
name: keyof typeof entityDefinitions,
|
||||
payload: Record<string, any>,
|
||||
insert = false,
|
||||
) {
|
||||
const properties = entityDefinitions[name].properties;
|
||||
const data = Object.fromEntries(
|
||||
Object.entries(payload).filter(
|
||||
([key, value]) => key in properties && value !== undefined,
|
||||
),
|
||||
);
|
||||
for (const [key, value] of Object.entries(data)) {
|
||||
if ((properties as any)[key].type === 'json' && value !== null)
|
||||
data[key] = JSON.parse(JSON.stringify(value));
|
||||
}
|
||||
const now = new Date();
|
||||
if (insert && !data.createdAt) data.createdAt = now;
|
||||
data.updatedAt = now;
|
||||
return data;
|
||||
}
|
||||
|
||||
function plain(name: keyof typeof entityDefinitions, row: any) {
|
||||
if (!row) return null;
|
||||
return Object.fromEntries(
|
||||
Object.keys(entityDefinitions[name].properties)
|
||||
.filter((key) => row[key] !== undefined)
|
||||
.map((key) => [key, row[key]]),
|
||||
);
|
||||
}
|
||||
|
||||
async function execute(
|
||||
operation: string,
|
||||
args: any[],
|
||||
token?: number,
|
||||
): Promise<any> {
|
||||
await ready;
|
||||
// Reject queued work after owner death; the monitor interrupts running SQL.
|
||||
if (process.ppid !== workerData.ownerPid) process.exit(1);
|
||||
const connection = orm.em.getConnection();
|
||||
if (operation === 'begin') {
|
||||
await connection.execute(
|
||||
transactions.length ? `SAVEPOINT "ql_${token}"` : 'BEGIN IMMEDIATE',
|
||||
);
|
||||
transactions.push(token!);
|
||||
return;
|
||||
}
|
||||
if (token !== transactions[transactions.length - 1])
|
||||
throw new Error('Database transaction ownership mismatch');
|
||||
if (operation === 'commit' || operation === 'rollback') {
|
||||
if (!transactions.length) throw new Error('No active database transaction');
|
||||
const nested = transactions.length > 1;
|
||||
if (operation === 'rollback' && nested)
|
||||
await connection.execute(`ROLLBACK TO SAVEPOINT "ql_${token}"`);
|
||||
await connection.execute(
|
||||
nested ? `RELEASE SAVEPOINT "ql_${token}"` : operation.toUpperCase(),
|
||||
);
|
||||
transactions.pop();
|
||||
return;
|
||||
}
|
||||
if (operation === 'close') {
|
||||
if (transactions.length)
|
||||
throw new Error('Cannot close an active transaction');
|
||||
cache?.close();
|
||||
await orm.close();
|
||||
return;
|
||||
}
|
||||
if (operation === 'query') return connection.execute(args[0], args[1]);
|
||||
if (operation === 'cache') {
|
||||
if (!workerData.cacheStorage)
|
||||
throw new Error('No cache database configured');
|
||||
if (!cache) {
|
||||
const { DatabaseSync } = require('node:sqlite');
|
||||
mkdirSync(dirname(workerData.cacheStorage), { recursive: true });
|
||||
cache = new DatabaseSync(workerData.cacheStorage);
|
||||
cache.exec(
|
||||
'PRAGMA busy_timeout=10000;CREATE TABLE IF NOT EXISTS keyv(key VARCHAR(255) PRIMARY KEY,value TEXT)',
|
||||
);
|
||||
}
|
||||
const [action, key, value] = args;
|
||||
switch (action) {
|
||||
case 'get':
|
||||
return cache.prepare('SELECT value FROM keyv WHERE key=?').get(key)
|
||||
?.value;
|
||||
case 'set':
|
||||
cache
|
||||
.prepare(
|
||||
'INSERT INTO keyv(key,value) VALUES(?,?) ON CONFLICT(key) DO UPDATE SET value=excluded.value',
|
||||
)
|
||||
.run(key, value);
|
||||
return true;
|
||||
case 'delete':
|
||||
return (
|
||||
cache.prepare('DELETE FROM keyv WHERE key=?').run(key).changes > 0
|
||||
);
|
||||
default:
|
||||
throw new Error('Unsupported cache operation');
|
||||
}
|
||||
}
|
||||
const [name, condition, options = {}] = args as [
|
||||
keyof typeof entityDefinitions,
|
||||
any,
|
||||
any,
|
||||
];
|
||||
if (!(name in entityDefinitions)) throw new Error('Unknown entity');
|
||||
const em = orm.em.fork();
|
||||
const entityName = entities.find((entity) => entity.meta.className === name)!;
|
||||
if (operation !== 'insert' && condition == null)
|
||||
throw new Error('Missing database predicate');
|
||||
const query = operation === 'insert' ? {} : filter(name, condition);
|
||||
const readOptions = {
|
||||
...options,
|
||||
orderBy: options.orderBy?.map((order: Record<string, string>) =>
|
||||
Object.fromEntries(
|
||||
Object.entries(order).map(([field, direction]) => [
|
||||
name === 'Env' && field === 'isPinned'
|
||||
? raw('COALESCE("isPinned",0)')
|
||||
: field,
|
||||
direction,
|
||||
]),
|
||||
),
|
||||
),
|
||||
};
|
||||
switch (operation) {
|
||||
case 'find':
|
||||
return (await em.find(entityName, query, readOptions)).map((row) =>
|
||||
plain(name, row),
|
||||
);
|
||||
case 'findOne':
|
||||
return plain(name, await em.findOne(entityName, query, readOptions));
|
||||
case 'count':
|
||||
return em.count(entityName, query);
|
||||
case 'insert': {
|
||||
const id = await em.insert(entityName, values(name, condition, true));
|
||||
return plain(name, await em.findOneOrFail(entityName, { id }));
|
||||
}
|
||||
case 'nativeUpdate':
|
||||
return em.nativeUpdate(entityName, query, values(name, options));
|
||||
case 'nativeDelete':
|
||||
return em.nativeDelete(entityName, query);
|
||||
default:
|
||||
throw new Error('Unsupported database operation');
|
||||
}
|
||||
}
|
||||
|
||||
export function startDatabaseWorker(settings: typeof workerData) {
|
||||
workerData = settings;
|
||||
ready = initialize();
|
||||
void ready.catch(() => {});
|
||||
let queue = Promise.resolve();
|
||||
process.on('message', ({ id, operation, args, token }) => {
|
||||
// Continue after a failed statement so the owner can still roll back.
|
||||
queue = queue.then(async () => {
|
||||
try {
|
||||
process.send?.({
|
||||
id,
|
||||
value: await execute(operation, args, token),
|
||||
});
|
||||
} catch (error: any) {
|
||||
const code =
|
||||
error.name === 'UniqueConstraintViolationException'
|
||||
? 'UNIQUE_CONSTRAINT'
|
||||
: error.name === 'TableNotFoundException'
|
||||
? 'DATABASE_SCHEMA_MISSING'
|
||||
: (
|
||||
{
|
||||
5: 'SQLITE_BUSY',
|
||||
6: 'SQLITE_LOCKED',
|
||||
8: 'SQLITE_READONLY',
|
||||
10: 'SQLITE_IOERR',
|
||||
11: 'SQLITE_CORRUPT',
|
||||
13: 'SQLITE_FULL',
|
||||
14: 'SQLITE_CANTOPEN',
|
||||
26: 'SQLITE_NOTADB',
|
||||
} as Record<number, string>
|
||||
)[Number(error.errcode) & 255] || 'DATABASE_QUERY_FAILED';
|
||||
process.send?.({
|
||||
id,
|
||||
error: {
|
||||
code,
|
||||
message:
|
||||
code === 'UNIQUE_CONSTRAINT'
|
||||
? 'Resource already exists'
|
||||
: `Database operation failed (${code})`,
|
||||
},
|
||||
});
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
+3
-16
@@ -1,5 +1,4 @@
|
||||
import { sequelize } from '.';
|
||||
import { DataTypes, Model, ModelDefined } from 'sequelize';
|
||||
import { Repository, RecordRow } from './repository';
|
||||
|
||||
export class Dependence {
|
||||
timestamp?: string;
|
||||
@@ -47,17 +46,5 @@ export enum versionDependenceCommandTypes {
|
||||
'=',
|
||||
}
|
||||
|
||||
export interface DependenceInstance
|
||||
extends Model<Dependence, Dependence>,
|
||||
Dependence {}
|
||||
export const DependenceModel = sequelize.define<DependenceInstance>(
|
||||
'Dependence',
|
||||
{
|
||||
name: DataTypes.STRING,
|
||||
type: DataTypes.NUMBER,
|
||||
timestamp: DataTypes.STRING,
|
||||
status: DataTypes.NUMBER,
|
||||
log: DataTypes.JSON,
|
||||
remark: DataTypes.STRING,
|
||||
},
|
||||
);
|
||||
export type DependenceInstance = RecordRow<Dependence>;
|
||||
export const DependenceModel = new Repository<Dependence>('Dependence');
|
||||
|
||||
+3
-13
@@ -1,5 +1,4 @@
|
||||
import { DataTypes, Model } from 'sequelize';
|
||||
import { sequelize } from '.';
|
||||
import { Repository, RecordRow } from './repository';
|
||||
|
||||
export class Env {
|
||||
value?: string;
|
||||
@@ -38,14 +37,5 @@ export const initPosition = 4500000000000000;
|
||||
export const stepPosition = 10000000000;
|
||||
export const minPosition = 100;
|
||||
|
||||
export interface EnvInstance extends Model<Env, Env>, Env {}
|
||||
export const EnvModel = sequelize.define<EnvInstance>('Env', {
|
||||
value: { type: DataTypes.STRING, unique: 'compositeIndex' },
|
||||
timestamp: DataTypes.STRING,
|
||||
status: DataTypes.NUMBER,
|
||||
position: DataTypes.NUMBER,
|
||||
name: { type: DataTypes.STRING, unique: 'compositeIndex' },
|
||||
remarks: DataTypes.STRING,
|
||||
isPinned: DataTypes.NUMBER,
|
||||
labels: DataTypes.JSON,
|
||||
});
|
||||
export type EnvInstance = RecordRow<Env>;
|
||||
export const EnvModel = new Repository<Env>('Env');
|
||||
|
||||
+5
-44
@@ -1,49 +1,10 @@
|
||||
import { Sequelize, Transaction } from 'sequelize';
|
||||
import config from '../config/index';
|
||||
import type { Database } from 'sqlite3';
|
||||
import { join } from 'path';
|
||||
import { DatabaseClient } from './databaseClient';
|
||||
|
||||
export const sequelize = new Sequelize({
|
||||
dialect: 'sqlite',
|
||||
storage: join(config.dbPath, 'database.sqlite'),
|
||||
logging: false,
|
||||
retry: {
|
||||
max: 10,
|
||||
match: ['SQLITE_BUSY: database is locked'],
|
||||
},
|
||||
pool: {
|
||||
max: 5,
|
||||
min: 2,
|
||||
idle: 30000,
|
||||
acquire: 30000,
|
||||
evict: 10000,
|
||||
},
|
||||
transactionType: Transaction.TYPES.IMMEDIATE,
|
||||
});
|
||||
|
||||
// In DELETE journal mode, EXTRA flushes the unlink that makes a transaction
|
||||
// final. Sequelize opens a separate SQLite handle for each transaction.
|
||||
const initialized = new WeakMap<Database, Promise<void>>();
|
||||
sequelize.addHook('beforeQuery', async (_options, query) => {
|
||||
const connection = query.connection as Database;
|
||||
let ready = initialized.get(connection);
|
||||
if (!ready) {
|
||||
ready = new Promise<void>((resolve, reject) => {
|
||||
connection.run('PRAGMA synchronous=EXTRA', error => error ? reject(error) : resolve());
|
||||
}).catch(error => {
|
||||
initialized.delete(connection);
|
||||
throw error;
|
||||
});
|
||||
initialized.set(connection, ready);
|
||||
}
|
||||
await ready;
|
||||
});
|
||||
|
||||
// SQLite transactions use dedicated file handles outside Sequelize 6's pool.
|
||||
// Its default destroyConnection targets the pool on COMMIT/ROLLBACK errors,
|
||||
// leaving the native writer open. The SQLite release path closes that handle.
|
||||
sequelize.connectionManager.destroyConnection = async (connection) => {
|
||||
sequelize.connectionManager.releaseConnection(connection);
|
||||
};
|
||||
export const database = new DatabaseClient(
|
||||
join(config.dbPath, 'database.sqlite'),
|
||||
join(config.dbPath, 'keyv.sqlite'),
|
||||
);
|
||||
|
||||
export type ResponseType<T> = { code: number; data?: T; message?: string };
|
||||
|
||||
+5
-23
@@ -1,5 +1,4 @@
|
||||
import { sequelize } from '.';
|
||||
import { DataTypes, Model, ModelDefined } from 'sequelize';
|
||||
import { Repository, RecordRow } from './repository';
|
||||
|
||||
export class App {
|
||||
name: string;
|
||||
@@ -25,30 +24,13 @@ export interface AppToken {
|
||||
}
|
||||
|
||||
export type AppScope =
|
||||
| 'crons'
|
||||
| 'crons:read'
|
||||
| 'subscriptions'
|
||||
| 'subscriptions:read'
|
||||
| 'envs'
|
||||
| 'envs:read'
|
||||
| 'crons'
|
||||
| 'configs'
|
||||
| 'configs:read'
|
||||
| 'scripts'
|
||||
| 'scripts:read'
|
||||
| 'logs'
|
||||
| 'logs:read'
|
||||
| 'dependencies'
|
||||
| 'dependencies:read'
|
||||
| 'dashboard'
|
||||
| 'dashboard:read'
|
||||
| 'system'
|
||||
| 'apps';
|
||||
| 'dashboard';
|
||||
|
||||
export interface AppInstance extends Model<App, App>, App {}
|
||||
export const AppModel = sequelize.define<AppInstance>('App', {
|
||||
name: { type: DataTypes.STRING, unique: 'name' },
|
||||
scopes: DataTypes.JSON,
|
||||
client_id: DataTypes.STRING,
|
||||
client_secret: DataTypes.STRING,
|
||||
tokens: DataTypes.JSON,
|
||||
});
|
||||
export type AppInstance = RecordRow<App>;
|
||||
export const AppModel = new Repository<App>('App');
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
export type Query = Record<string, any>;
|
||||
export type QuerySpec = {
|
||||
where: Query;
|
||||
orderBy?: Record<string, string>[];
|
||||
offset?: number;
|
||||
limit?: number;
|
||||
};
|
||||
|
||||
export function orderBy(order: string[][]): Record<string, string>[] {
|
||||
return order.map(([field, direction]) => {
|
||||
if (!/^(asc|desc)$/i.test(direction))
|
||||
throw new Error('Invalid sort direction');
|
||||
return { [field]: direction.toLowerCase() };
|
||||
});
|
||||
}
|
||||
|
||||
export function textSearch(fields: string[], text: string): Query {
|
||||
return {
|
||||
$or: fields.flatMap((field) =>
|
||||
[...new Set([text, encodeURI(text)])].map((value) => ({
|
||||
[field]: { $like: `%${value}%` },
|
||||
})),
|
||||
),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
import { database } from '.';
|
||||
import { DatabaseClient } from './databaseClient';
|
||||
|
||||
export type RecordRow<T> = T & { id: number; createdAt: Date; updatedAt: Date };
|
||||
export type Query = Record<string, any>;
|
||||
export type ReadOptions = {
|
||||
fields?: string[];
|
||||
orderBy?: Record<string, string>[];
|
||||
limit?: number;
|
||||
offset?: number;
|
||||
};
|
||||
|
||||
// A small IPC boundary with MikroORM's native query/operation names. No ORM
|
||||
// entities or request identity maps escape the single database worker.
|
||||
export class Repository<T> {
|
||||
constructor(
|
||||
private name: string,
|
||||
private client: () => DatabaseClient = () => database,
|
||||
) {}
|
||||
find(where: Query = {}, options: ReadOptions = {}): Promise<RecordRow<T>[]> {
|
||||
return this.client().request('find', this.name, where, options);
|
||||
}
|
||||
findOne(
|
||||
where: Query,
|
||||
options: ReadOptions = {},
|
||||
): Promise<RecordRow<T> | null> {
|
||||
return this.client().request('findOne', this.name, where, options);
|
||||
}
|
||||
count(where: Query = {}): Promise<number> {
|
||||
return this.client().request('count', this.name, where);
|
||||
}
|
||||
insert(data: Partial<T>): Promise<RecordRow<T>> {
|
||||
return this.client().request('insert', this.name, data);
|
||||
}
|
||||
nativeUpdate(where: Query, data: Partial<T>): Promise<number> {
|
||||
return this.client().request('nativeUpdate', this.name, where, data);
|
||||
}
|
||||
nativeDelete(where: Query): Promise<number> {
|
||||
return this.client().request('nativeDelete', this.name, where);
|
||||
}
|
||||
async insertMany(data: Partial<T>[]): Promise<RecordRow<T>[]> {
|
||||
return this.client().transaction(async () => {
|
||||
const rows = [];
|
||||
for (const item of data) rows.push(await this.insert(item));
|
||||
return rows;
|
||||
});
|
||||
}
|
||||
async getOrCreate(where: Query): Promise<RecordRow<T>> {
|
||||
return this.client().transaction(
|
||||
async () =>
|
||||
(await this.findOne(where)) || this.insert(where as Partial<T>),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,12 +1,10 @@
|
||||
import { sequelize } from '.';
|
||||
import { DataTypes, Model } from 'sequelize';
|
||||
import { Repository, RecordRow } from './repository';
|
||||
|
||||
export enum InstanceStatus {
|
||||
'running' = 0,
|
||||
'finished' = 1,
|
||||
'stopped' = 2,
|
||||
'error' = 3,
|
||||
'unknown' = 4,
|
||||
}
|
||||
|
||||
export interface RunningInstanceAttributes {
|
||||
@@ -42,42 +40,7 @@ export class RunningInstance {
|
||||
}
|
||||
}
|
||||
|
||||
export interface RunningInstanceModel
|
||||
extends Model<RunningInstanceAttributes, RunningInstanceAttributes>,
|
||||
RunningInstanceAttributes {}
|
||||
|
||||
export const RunningInstanceModel = sequelize.define<RunningInstanceModel>(
|
||||
export type RunningInstanceModel = RecordRow<RunningInstanceAttributes>;
|
||||
export const RunningInstanceModel = new Repository<RunningInstanceAttributes>(
|
||||
'RunningInstance',
|
||||
{
|
||||
cron_id: {
|
||||
type: DataTypes.NUMBER,
|
||||
allowNull: false,
|
||||
},
|
||||
pid: {
|
||||
type: DataTypes.NUMBER,
|
||||
allowNull: true,
|
||||
},
|
||||
log_path: {
|
||||
type: DataTypes.STRING,
|
||||
allowNull: true,
|
||||
},
|
||||
started_at: {
|
||||
type: DataTypes.NUMBER,
|
||||
allowNull: false,
|
||||
},
|
||||
finished_at: {
|
||||
type: DataTypes.NUMBER,
|
||||
allowNull: true,
|
||||
},
|
||||
status: {
|
||||
type: DataTypes.NUMBER,
|
||||
allowNull: false,
|
||||
defaultValue: InstanceStatus.running,
|
||||
},
|
||||
exit_code: {
|
||||
type: DataTypes.NUMBER,
|
||||
allowNull: true,
|
||||
},
|
||||
},
|
||||
{ indexes: [{ fields: ['cron_id', 'pid', 'started_at'] }, { fields: ['cron_id', 'id'] }] },
|
||||
);
|
||||
|
||||
@@ -0,0 +1,178 @@
|
||||
// Persisted SQLite names and types are part of the rollback contract.
|
||||
type Field = {
|
||||
type: string;
|
||||
fieldName: string;
|
||||
nullable?: boolean;
|
||||
primary?: boolean;
|
||||
autoincrement?: boolean;
|
||||
};
|
||||
function entity<Name extends string>(
|
||||
name: Name,
|
||||
tableName: string,
|
||||
groups: Record<string, string[]>,
|
||||
required: string[] = [],
|
||||
) {
|
||||
const properties: Record<string, Field> = {
|
||||
id: { type: 'number', fieldName: 'id', primary: true, autoincrement: true },
|
||||
};
|
||||
for (const [type, fields] of Object.entries(groups))
|
||||
for (const field of fields)
|
||||
properties[field] = {
|
||||
type,
|
||||
fieldName: field,
|
||||
nullable: !required.includes(field),
|
||||
};
|
||||
for (const field of ['createdAt', 'updatedAt'])
|
||||
properties[field] = {
|
||||
type: 'legacyDate',
|
||||
fieldName: field,
|
||||
nullable: false,
|
||||
};
|
||||
return { name, tableName, properties };
|
||||
}
|
||||
export const entityDefinitions = {
|
||||
App: entity(
|
||||
'App',
|
||||
'Apps',
|
||||
{
|
||||
string: ['name', 'client_id', 'client_secret'],
|
||||
json: ['scopes', 'tokens'],
|
||||
},
|
||||
[],
|
||||
),
|
||||
Auth: entity('Auth', 'Auths', { string: ['ip', 'type'], json: ['info'] }, []),
|
||||
CrontabStat: entity(
|
||||
'CrontabStat',
|
||||
'CrontabStats',
|
||||
{
|
||||
number: [
|
||||
'ref_id',
|
||||
'run_count',
|
||||
'success_count',
|
||||
'fail_count',
|
||||
'total_time',
|
||||
'max_time',
|
||||
],
|
||||
string: ['date'],
|
||||
},
|
||||
['ref_id', 'date'],
|
||||
),
|
||||
CrontabView: entity(
|
||||
'CrontabView',
|
||||
'CrontabViews',
|
||||
{
|
||||
string: ['name', 'filterRelation'],
|
||||
number: ['position', 'isDisabled', 'type'],
|
||||
json: ['filters', 'sorts'],
|
||||
},
|
||||
[],
|
||||
),
|
||||
Crontab: entity(
|
||||
'Crontab',
|
||||
'Crontabs',
|
||||
{
|
||||
string: [
|
||||
'name',
|
||||
'command',
|
||||
'schedule',
|
||||
'timestamp',
|
||||
'log_path',
|
||||
'queued_token',
|
||||
'task_before',
|
||||
'task_after',
|
||||
'log_name',
|
||||
'work_dir',
|
||||
],
|
||||
boolean: ['saved'],
|
||||
number: [
|
||||
'status',
|
||||
'isSystem',
|
||||
'pid',
|
||||
'isDisabled',
|
||||
'isPinned',
|
||||
'last_running_time',
|
||||
'last_execution_time',
|
||||
'sub_id',
|
||||
'allow_multiple_instances',
|
||||
],
|
||||
json: ['labels', 'extra_schedules'],
|
||||
},
|
||||
[],
|
||||
),
|
||||
Dependence: entity(
|
||||
'Dependence',
|
||||
'Dependences',
|
||||
{
|
||||
string: ['name', 'timestamp', 'remark'],
|
||||
number: ['type', 'status'],
|
||||
json: ['log'],
|
||||
},
|
||||
[],
|
||||
),
|
||||
Env: entity(
|
||||
'Env',
|
||||
'Envs',
|
||||
{
|
||||
string: ['value', 'timestamp', 'name', 'remarks'],
|
||||
number: ['status', 'position', 'isPinned'],
|
||||
json: ['labels'],
|
||||
},
|
||||
[],
|
||||
),
|
||||
RunningInstance: entity(
|
||||
'RunningInstance',
|
||||
'RunningInstances',
|
||||
{
|
||||
number: [
|
||||
'cron_id',
|
||||
'pid',
|
||||
'started_at',
|
||||
'finished_at',
|
||||
'status',
|
||||
'exit_code',
|
||||
],
|
||||
string: ['log_path'],
|
||||
},
|
||||
['cron_id', 'started_at', 'status'],
|
||||
),
|
||||
Subscription: entity(
|
||||
'Subscription',
|
||||
'Subscriptions',
|
||||
{
|
||||
string: [
|
||||
'name',
|
||||
'url',
|
||||
'schedule',
|
||||
'type',
|
||||
'whitelist',
|
||||
'blacklist',
|
||||
'dependences',
|
||||
'extensions',
|
||||
'sub_before',
|
||||
'sub_after',
|
||||
'branch',
|
||||
'pull_type',
|
||||
'log_path',
|
||||
'schedule_type',
|
||||
'alias',
|
||||
'proxy',
|
||||
],
|
||||
json: ['interval_schedule', 'pull_option'],
|
||||
number: ['status', 'pid', 'is_disabled', 'autoAddCron', 'autoDelCron'],
|
||||
},
|
||||
[],
|
||||
),
|
||||
};
|
||||
export const initialSchema = [
|
||||
'CREATE TABLE IF NOT EXISTS `Apps` (`id` INTEGER PRIMARY KEY AUTOINCREMENT, `name` VARCHAR(255), `scopes` JSON, `client_id` VARCHAR(255), `client_secret` VARCHAR(255), `tokens` JSON, `createdAt` DATETIME NOT NULL, `updatedAt` DATETIME NOT NULL, UNIQUE (`name`))',
|
||||
'CREATE TABLE IF NOT EXISTS `Auths` (`id` INTEGER PRIMARY KEY AUTOINCREMENT, `ip` VARCHAR(255), `type` VARCHAR(255), `info` JSON, `createdAt` DATETIME NOT NULL, `updatedAt` DATETIME NOT NULL)',
|
||||
'CREATE TABLE IF NOT EXISTS `CrontabStats` (`id` INTEGER PRIMARY KEY AUTOINCREMENT, `ref_id` NUMBER NOT NULL, `date` VARCHAR(255) NOT NULL, `run_count` NUMBER DEFAULT 0, `success_count` NUMBER DEFAULT 0, `fail_count` NUMBER DEFAULT 0, `total_time` NUMBER DEFAULT 0, `max_time` NUMBER DEFAULT 0, `createdAt` DATETIME NOT NULL, `updatedAt` DATETIME NOT NULL)',
|
||||
'CREATE TABLE IF NOT EXISTS `CrontabViews` (`id` INTEGER PRIMARY KEY AUTOINCREMENT, `name` VARCHAR(255), `position` NUMBER, `isDisabled` NUMBER, `filters` JSON, `sorts` JSON, `filterRelation` VARCHAR(255), `type` NUMBER, `createdAt` DATETIME NOT NULL, `updatedAt` DATETIME NOT NULL, UNIQUE (`name`))',
|
||||
'CREATE TABLE IF NOT EXISTS `Crontabs` (`id` INTEGER PRIMARY KEY AUTOINCREMENT, `name` VARCHAR(255), `command` VARCHAR(255), `schedule` VARCHAR(255), `timestamp` VARCHAR(255), `saved` TINYINT(1), `status` NUMBER, `isSystem` NUMBER, `pid` NUMBER, `isDisabled` NUMBER, `isPinned` NUMBER, `log_path` VARCHAR(255), `queued_token` VARCHAR(255), `labels` JSON, `last_running_time` NUMBER, `last_execution_time` NUMBER, `sub_id` NUMBER, `extra_schedules` JSON, `task_before` VARCHAR(255), `task_after` VARCHAR(255), `log_name` VARCHAR(255), `allow_multiple_instances` NUMBER, `work_dir` VARCHAR(255), `createdAt` DATETIME NOT NULL, `updatedAt` DATETIME NOT NULL, UNIQUE (`name`, `command`, `schedule`))',
|
||||
'CREATE TABLE IF NOT EXISTS `Dependences` (`id` INTEGER PRIMARY KEY AUTOINCREMENT, `name` VARCHAR(255), `type` NUMBER, `timestamp` VARCHAR(255), `status` NUMBER, `log` JSON, `remark` VARCHAR(255), `createdAt` DATETIME NOT NULL, `updatedAt` DATETIME NOT NULL)',
|
||||
'CREATE TABLE IF NOT EXISTS `Envs` (`id` INTEGER PRIMARY KEY AUTOINCREMENT, `value` VARCHAR(255), `timestamp` VARCHAR(255), `status` NUMBER, `position` NUMBER, `name` VARCHAR(255), `remarks` VARCHAR(255), `isPinned` NUMBER, `labels` JSON, `createdAt` DATETIME NOT NULL, `updatedAt` DATETIME NOT NULL, UNIQUE (`value`, `name`))',
|
||||
'CREATE TABLE IF NOT EXISTS `RunningInstances` (`id` INTEGER PRIMARY KEY AUTOINCREMENT, `cron_id` NUMBER NOT NULL, `pid` NUMBER, `log_path` VARCHAR(255), `started_at` NUMBER NOT NULL, `finished_at` NUMBER, `status` NUMBER NOT NULL DEFAULT 0, `exit_code` NUMBER, `createdAt` DATETIME NOT NULL, `updatedAt` DATETIME NOT NULL)',
|
||||
'CREATE TABLE IF NOT EXISTS `Subscriptions` (`id` INTEGER PRIMARY KEY AUTOINCREMENT, `name` VARCHAR(255), `url` VARCHAR(255), `schedule` VARCHAR(255), `interval_schedule` JSON, `type` VARCHAR(255), `whitelist` VARCHAR(255), `blacklist` VARCHAR(255), `status` NUMBER, `dependences` VARCHAR(255), `extensions` VARCHAR(255), `sub_before` VARCHAR(255), `sub_after` VARCHAR(255), `branch` VARCHAR(255), `pull_type` VARCHAR(255), `pull_option` JSON, `pid` NUMBER, `is_disabled` NUMBER, `log_path` VARCHAR(255), `schedule_type` VARCHAR(255), `alias` VARCHAR(255), `proxy` VARCHAR(255), `autoAddCron` NUMBER, `autoDelCron` NUMBER, `createdAt` DATETIME NOT NULL, `updatedAt` DATETIME NOT NULL, UNIQUE (`name`, `url`, `schedule`, `interval_schedule`), UNIQUE (`alias`))',
|
||||
'CREATE INDEX IF NOT EXISTS `crontab_stats_date` ON `CrontabStats` (`date`)',
|
||||
'CREATE UNIQUE INDEX IF NOT EXISTS `crontab_stats_ref_id_date` ON `CrontabStats` (`ref_id`, `date`)',
|
||||
];
|
||||
@@ -0,0 +1,45 @@
|
||||
import { database } from '.';
|
||||
|
||||
// Aggregate SQL stays explicit and bound; public input is never used as an SQL
|
||||
// identifier. These queries preserve the dashboard response names.
|
||||
export const statistics = {
|
||||
async totals(date: string) {
|
||||
const rows = await database.query(
|
||||
`SELECT SUM(run_count) AS total_runs,
|
||||
SUM(success_count) AS total_success, SUM(fail_count) AS total_fail,
|
||||
SUM(total_time) AS total_time FROM CrontabStats WHERE date=?`,
|
||||
[date],
|
||||
);
|
||||
return rows[0];
|
||||
},
|
||||
results(date: string, column: 'success_count' | 'fail_count') {
|
||||
if (!['success_count', 'fail_count'].includes(column))
|
||||
throw new Error('Invalid statistic');
|
||||
return database.query(
|
||||
`SELECT ref_id,SUM(${column}) AS result_count FROM CrontabStats
|
||||
WHERE date=? AND ${column}>0 GROUP BY ref_id ORDER BY result_count DESC,ref_id ASC`,
|
||||
[date],
|
||||
);
|
||||
},
|
||||
trend(dates: string[]) {
|
||||
if (!dates.length) return Promise.resolve([]);
|
||||
return database.query(
|
||||
`SELECT date,SUM(run_count) AS total_runs,
|
||||
SUM(success_count) AS total_success,SUM(fail_count) AS total_fail FROM CrontabStats
|
||||
WHERE date IN (${dates
|
||||
.map(() => '?')
|
||||
.join(',')}) GROUP BY date ORDER BY date ASC`,
|
||||
dates,
|
||||
);
|
||||
},
|
||||
ranking(date: string, metric: 'total_time' | 'run_count') {
|
||||
if (!['total_time', 'run_count'].includes(metric))
|
||||
throw new Error('Invalid statistic');
|
||||
return database.query(
|
||||
`SELECT ref_id,SUM(total_time) AS total_time,SUM(run_count) AS run_count,
|
||||
SUM(success_count) AS success_count,MAX(max_time) AS max_time FROM CrontabStats
|
||||
WHERE date=? AND run_count>0 GROUP BY ref_id ORDER BY SUM(${metric}) DESC LIMIT 5`,
|
||||
[date],
|
||||
);
|
||||
},
|
||||
};
|
||||
@@ -1,5 +1,4 @@
|
||||
import { sequelize } from '.';
|
||||
import { DataTypes, Model, ModelDefined } from 'sequelize';
|
||||
import { Repository, RecordRow } from './repository';
|
||||
import { SimpleIntervalSchedule } from 'toad-scheduler';
|
||||
|
||||
type SimpleIntervalScheduleUnit = keyof SimpleIntervalSchedule;
|
||||
@@ -70,46 +69,5 @@ export enum SubscriptionStatus {
|
||||
'queued',
|
||||
}
|
||||
|
||||
export interface SubscriptionInstance
|
||||
extends Model<Subscription, Subscription>,
|
||||
Subscription {}
|
||||
export const SubscriptionModel = sequelize.define<SubscriptionInstance>(
|
||||
'Subscription',
|
||||
{
|
||||
name: {
|
||||
unique: 'compositeIndex',
|
||||
type: DataTypes.STRING,
|
||||
},
|
||||
url: {
|
||||
unique: 'compositeIndex',
|
||||
type: DataTypes.STRING,
|
||||
},
|
||||
schedule: {
|
||||
unique: 'compositeIndex',
|
||||
type: DataTypes.STRING,
|
||||
},
|
||||
interval_schedule: {
|
||||
unique: 'compositeIndex',
|
||||
type: DataTypes.JSON,
|
||||
},
|
||||
type: DataTypes.STRING,
|
||||
whitelist: DataTypes.STRING,
|
||||
blacklist: DataTypes.STRING,
|
||||
status: DataTypes.NUMBER,
|
||||
dependences: DataTypes.STRING,
|
||||
extensions: DataTypes.STRING,
|
||||
sub_before: DataTypes.STRING,
|
||||
sub_after: DataTypes.STRING,
|
||||
branch: DataTypes.STRING,
|
||||
pull_type: DataTypes.STRING,
|
||||
pull_option: DataTypes.JSON,
|
||||
pid: DataTypes.NUMBER,
|
||||
is_disabled: DataTypes.NUMBER,
|
||||
log_path: DataTypes.STRING,
|
||||
schedule_type: DataTypes.STRING,
|
||||
alias: { type: DataTypes.STRING, unique: 'alias' },
|
||||
proxy: { type: DataTypes.STRING, allowNull: true },
|
||||
autoAddCron: { type: DataTypes.NUMBER, allowNull: true },
|
||||
autoDelCron: { type: DataTypes.NUMBER, allowNull: true },
|
||||
},
|
||||
);
|
||||
export type SubscriptionInstance = RecordRow<Subscription>;
|
||||
export const SubscriptionModel = new Repository<Subscription>('Subscription');
|
||||
|
||||
+3
-13
@@ -1,5 +1,4 @@
|
||||
import { sequelize } from '.';
|
||||
import { DataTypes, Model, ModelDefined } from 'sequelize';
|
||||
import { Repository, RecordRow } from './repository';
|
||||
import { NotificationInfo } from './notify';
|
||||
|
||||
export class SystemInfo {
|
||||
@@ -106,14 +105,5 @@ export type SystemModelInfo = SystemConfigInfo &
|
||||
Partial<NotifyLogInfo> &
|
||||
Partial<AuthInfo>;
|
||||
|
||||
export interface SystemInstance
|
||||
extends Model<SystemInfo, SystemInfo>,
|
||||
SystemInfo {}
|
||||
export const SystemModel = sequelize.define<SystemInstance>('Auth', {
|
||||
ip: DataTypes.STRING,
|
||||
type: DataTypes.STRING,
|
||||
info: {
|
||||
type: DataTypes.JSON,
|
||||
allowNull: true,
|
||||
},
|
||||
});
|
||||
export type SystemInstance = RecordRow<SystemInfo>;
|
||||
export const SystemModel = new Repository<SystemInfo>('Auth');
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
{
|
||||
"extends": "../tsconfig.json",
|
||||
"compilerOptions": {
|
||||
"module": "node20",
|
||||
"moduleResolution": "node16",
|
||||
"rootDir": "..",
|
||||
"outDir": "../../static/build"
|
||||
},
|
||||
"include": ["./databaseWorker.ts", "./schema.ts"],
|
||||
"exclude": ["node_modules"]
|
||||
}
|
||||
+6
-22
@@ -1,30 +1,14 @@
|
||||
import Logger from './logger';
|
||||
import { EnvModel } from '../data/env';
|
||||
import { CrontabModel } from '../data/cron';
|
||||
import { DependenceModel } from '../data/dependence';
|
||||
import { AppModel } from '../data/open';
|
||||
import { SystemModel } from '../data/system';
|
||||
import { SubscriptionModel } from '../data/subscription';
|
||||
import { CrontabViewModel } from '../data/cronView';
|
||||
import { CrontabStatModel } from '../data/cronStats';
|
||||
import { RunningInstanceModel } from '../data/runningInstance';
|
||||
import { sequelize } from '../data';
|
||||
import { database } from '../data';
|
||||
import { initialSchema } from '../data/schema';
|
||||
import { migrateSchema } from '../shared/schemaMigrations';
|
||||
|
||||
export default async () => {
|
||||
try {
|
||||
await CrontabModel.sync();
|
||||
await DependenceModel.sync();
|
||||
await AppModel.sync();
|
||||
await SystemModel.sync();
|
||||
await EnvModel.sync();
|
||||
await SubscriptionModel.sync();
|
||||
await CrontabViewModel.sync();
|
||||
await CrontabStatModel.sync();
|
||||
await RunningInstanceModel.sync();
|
||||
|
||||
await migrateSchema(sequelize);
|
||||
|
||||
await database.transaction(async () => {
|
||||
for (const sql of initialSchema) await database.query(sql);
|
||||
await migrateSchema(database);
|
||||
});
|
||||
Logger.info('[boot] DB loaded');
|
||||
} catch (error) {
|
||||
Logger.error('[boot] DB load failed', error);
|
||||
|
||||
+55
-104
@@ -16,8 +16,7 @@ import { t } from '../shared/i18n';
|
||||
import { AppScope } from '../data/open';
|
||||
import uniqueConstraintError from '../middlewares/uniqueConstraintError';
|
||||
import protectedPathCase from '../middlewares/protectedPathCase';
|
||||
import Logger from './logger';
|
||||
|
||||
import { withAuthAvailability } from '../middlewares/authAvailability';
|
||||
function resolveTrustProxy(value = process.env.QL_TRUST_PROXY) {
|
||||
const setting = value?.trim();
|
||||
if (!setting) {
|
||||
@@ -31,24 +30,20 @@ function resolveTrustProxy(value = process.env.QL_TRUST_PROXY) {
|
||||
}
|
||||
return setting;
|
||||
}
|
||||
|
||||
export default ({ app }: { app: Application }) => {
|
||||
// Security: Enable strict routing to prevent case-insensitive path bypass
|
||||
app.set('case sensitive routing', true);
|
||||
app.set('strict routing', true);
|
||||
app.set('trust proxy', resolveTrustProxy());
|
||||
app.use(cors());
|
||||
|
||||
// Security: Reject case variations under protected API namespaces before
|
||||
// authentication checks can interpret the request differently from routing.
|
||||
app.use(protectedPathCase);
|
||||
|
||||
// Rewrite URLs to strip baseUrl prefix if configured
|
||||
// This allows the rest of the app to work without baseUrl awareness
|
||||
if (config.baseUrl) {
|
||||
app.use(rewrite(`${config.baseUrl}/*`, '/$1'));
|
||||
}
|
||||
|
||||
app.get(`${config.api.prefix}/env.js`, serveEnv);
|
||||
app.use(
|
||||
`${config.api.prefix}/static`,
|
||||
@@ -59,7 +54,6 @@ export default ({ app }: { app: Application }) => {
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
const credentialPaths = ['/api', '/open'].flatMap((prefix) =>
|
||||
['/user/login', '/user/init', '/user/two-factor/login'].map(
|
||||
(route) => `${prefix}${route}`,
|
||||
@@ -70,13 +64,10 @@ export default ({ app }: { app: Application }) => {
|
||||
bodyParser.json({ limit: '16kb' }),
|
||||
bodyParser.urlencoded({ limit: '16kb', extended: false }),
|
||||
);
|
||||
|
||||
app.use(bodyParser.json({ limit: '50mb' }));
|
||||
app.use(bodyParser.urlencoded({ limit: '50mb', extended: true }));
|
||||
|
||||
const frontendPath = path.join(config.rootPath, 'static/dist');
|
||||
app.use(express.static(frontendPath));
|
||||
|
||||
app.use(
|
||||
expressjwt({
|
||||
secret: config.jwt.secret,
|
||||
@@ -85,7 +76,6 @@ export default ({ app }: { app: Application }) => {
|
||||
path: [...config.apiWhiteList, /^(\/(?!api\/).*)$/i],
|
||||
}),
|
||||
);
|
||||
|
||||
app.use((req: Request, res, next) => {
|
||||
if (!req.headers) {
|
||||
req.platform = 'desktop';
|
||||
@@ -95,13 +85,12 @@ export default ({ app }: { app: Application }) => {
|
||||
}
|
||||
return next();
|
||||
});
|
||||
|
||||
app.use(async (req: Request, res, next) => {
|
||||
app.use(
|
||||
withAuthAvailability(async (req: Request, res, next) => {
|
||||
const pathLower = req.path.toLowerCase();
|
||||
if (!['/open/', '/api/'].some((x) => pathLower.startsWith(x))) {
|
||||
return next();
|
||||
}
|
||||
|
||||
const headerToken = getToken(req);
|
||||
if (pathLower.startsWith('/open/')) {
|
||||
const apps = await shareStore.getApps();
|
||||
@@ -112,50 +101,12 @@ export default ({ app }: { app: Application }) => {
|
||||
const currentToken = doc.tokens.find((x) => x.value === headerToken);
|
||||
const keyMatch = pathLower.match(/\/open\/([a-z]+)\/*/);
|
||||
const key = keyMatch && keyMatch[1];
|
||||
|
||||
const isReadRequest =
|
||||
(['GET', 'HEAD'].includes(req.method) &&
|
||||
!(
|
||||
key === 'crons' && /^\/open\/crons\/import\/?$/.test(pathLower)
|
||||
)) ||
|
||||
(['scripts', 'logs'].includes(key || '') &&
|
||||
req.method === 'POST' &&
|
||||
/^\/open\/(?:scripts|logs)\/(?:download|entries\/check)\/?$/.test(pathLower));
|
||||
const hasNamespaceScope =
|
||||
doc.scopes.includes(key as AppScope) ||
|
||||
([
|
||||
'crons',
|
||||
'subscriptions',
|
||||
'envs',
|
||||
'configs',
|
||||
'scripts',
|
||||
'logs',
|
||||
'dependencies',
|
||||
'dashboard',
|
||||
].includes(key || '') &&
|
||||
doc.scopes.includes(`${key}:read` as AppScope) &&
|
||||
isReadRequest);
|
||||
if (!hasNamespaceScope) {
|
||||
if (!doc.scopes.includes(key as AppScope)) {
|
||||
const err = new UnauthorizedError('credentials_bad_scheme', {
|
||||
message: t('暂无权限'),
|
||||
});
|
||||
return next(err);
|
||||
}
|
||||
|
||||
// The built-in system app still needs its local CLI maintenance API.
|
||||
const appRouteAllowed =
|
||||
key !== 'system' ||
|
||||
doc.name === 'system' ||
|
||||
((req.method === 'GET' || req.method === 'HEAD') &&
|
||||
(pathLower === '/open/system' || pathLower === '/open/system/')) ||
|
||||
(req.method === 'PUT' && pathLower === '/open/system/notify');
|
||||
if (!appRouteAllowed) {
|
||||
const err = new UnauthorizedError('credentials_bad_scheme', {
|
||||
message: t('暂无权限'),
|
||||
});
|
||||
return next(err);
|
||||
}
|
||||
|
||||
if (
|
||||
!currentToken ||
|
||||
currentToken.expiration < Math.round(Date.now() / 1000)
|
||||
@@ -165,11 +116,9 @@ export default ({ app }: { app: Application }) => {
|
||||
});
|
||||
return next(err);
|
||||
}
|
||||
|
||||
return next();
|
||||
}
|
||||
}
|
||||
|
||||
const originPath = `${req.baseUrl}${pathLower === '/' ? '' : pathLower}`;
|
||||
if (
|
||||
!headerToken &&
|
||||
@@ -178,37 +127,42 @@ export default ({ app }: { app: Application }) => {
|
||||
) {
|
||||
return next();
|
||||
}
|
||||
|
||||
const authInfo = await shareStore.getAuthInfo();
|
||||
if (isValidToken(authInfo, headerToken, req.platform, config.jwt.secret)) {
|
||||
if (
|
||||
isValidToken(authInfo, headerToken, req.platform, config.jwt.secret)
|
||||
) {
|
||||
return next();
|
||||
}
|
||||
|
||||
const errorCode = headerToken ? 'invalid_token' : 'credentials_required';
|
||||
const errorMessage = headerToken ? t('Token 已失效') : t('请先登录');
|
||||
const err = new UnauthorizedError(errorCode, { message: errorMessage });
|
||||
next(err);
|
||||
});
|
||||
|
||||
app.use(async (req, res, next) => {
|
||||
}),
|
||||
);
|
||||
app.use(
|
||||
withAuthAvailability(async (req, res, next) => {
|
||||
const pathLower = req.path.toLowerCase();
|
||||
if (!['/api/user/init', '/open/user/init'].includes(pathLower)) {
|
||||
if (
|
||||
![
|
||||
'/api/user/init',
|
||||
'/api/user/notification/init',
|
||||
'/open/user/init',
|
||||
'/open/user/notification/init',
|
||||
].includes(pathLower)
|
||||
) {
|
||||
return next();
|
||||
}
|
||||
const authInfo = (await shareStore.getAuthInfo()) || ({} as AuthInfo);
|
||||
|
||||
let isInitialized = !isDefaultAuthInfo(authInfo);
|
||||
|
||||
if (isInitialized) {
|
||||
return res.send({ code: 450, message: t('未知错误') });
|
||||
} else {
|
||||
return next();
|
||||
}
|
||||
});
|
||||
|
||||
}),
|
||||
);
|
||||
app.use(rewrite('/open/*', '/api/$1'));
|
||||
app.use(config.api.prefix, routes());
|
||||
|
||||
app.get('*', (req, res, next) => {
|
||||
// Don't serve index.html for API routes
|
||||
if (
|
||||
@@ -226,64 +180,61 @@ export default ({ app }: { app: Application }) => {
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
app.use(validationErrors);
|
||||
app.use(uniqueConstraintError);
|
||||
|
||||
app.use(
|
||||
(
|
||||
err: Error & { status: number; code?: string },
|
||||
err: Error & {
|
||||
status: number;
|
||||
},
|
||||
req: Request,
|
||||
res: Response,
|
||||
next: NextFunction,
|
||||
) => {
|
||||
if (err.name === 'UnauthorizedError') {
|
||||
let message = err.message;
|
||||
if (!config.isDevelopment) {
|
||||
if (err.code === 'credentials_bad_scheme') {
|
||||
message = t('暂无权限');
|
||||
} else if (err.code === 'credentials_required') {
|
||||
message = t('请先登录');
|
||||
} else {
|
||||
message = t('Token 已失效');
|
||||
}
|
||||
}
|
||||
return res.status(401).send({ code: 401, message }).end();
|
||||
return res
|
||||
.status(err.status)
|
||||
.send({ code: 401, message: err.message })
|
||||
.end();
|
||||
}
|
||||
return next(err);
|
||||
},
|
||||
);
|
||||
|
||||
app.use(
|
||||
(
|
||||
err: Error & { status: number },
|
||||
err: Error & {
|
||||
errors: any[];
|
||||
},
|
||||
req: Request,
|
||||
res: Response,
|
||||
next: NextFunction,
|
||||
) => {
|
||||
const status =
|
||||
Number.isInteger(err.status) && err.status >= 400 && err.status < 600
|
||||
? err.status
|
||||
: 500;
|
||||
if (status >= 500) {
|
||||
const route =
|
||||
typeof req.route?.path === 'string' ? req.route.path : '?';
|
||||
const errorName = /^[A-Za-z][A-Za-z0-9]{0,63}$/.test(err.name)
|
||||
? err.name
|
||||
: 'Error';
|
||||
Logger.error(
|
||||
'HTTP request failed: status=%d method=%s route=%s type=%s',
|
||||
status,
|
||||
req.method,
|
||||
route,
|
||||
errorName,
|
||||
);
|
||||
if (err.name === 'DatabaseError') {
|
||||
return res
|
||||
.status(500)
|
||||
.send({
|
||||
code: 400,
|
||||
message: `${err.message}`,
|
||||
errors: err.errors,
|
||||
})
|
||||
.end();
|
||||
}
|
||||
res.status(status);
|
||||
return next(err);
|
||||
},
|
||||
);
|
||||
app.use(
|
||||
(
|
||||
err: Error & {
|
||||
status: number;
|
||||
},
|
||||
req: Request,
|
||||
res: Response,
|
||||
next: NextFunction,
|
||||
) => {
|
||||
res.status(err.status || 500);
|
||||
res.json({
|
||||
code: status,
|
||||
message:
|
||||
!config.isDevelopment && status >= 500 ? t('未知错误') : err.message,
|
||||
code: err.status || 500,
|
||||
message: err.message,
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
+66
-77
@@ -1,11 +1,12 @@
|
||||
import { textSearch } from '../data/queries';
|
||||
import { Query, QuerySpec, orderBy } from '../data/queries';
|
||||
import DependenceService from '../services/dependence';
|
||||
import { exec } from 'child_process';
|
||||
import { Container } from 'typedi';
|
||||
import { Crontab, CrontabModel } from '../data/cron';
|
||||
import { Crontab, CrontabModel, CrontabStatus } from '../data/cron';
|
||||
import CronService from '../services/cron';
|
||||
import EnvService from '../services/env';
|
||||
import { DependenceModel, DependenceStatus } from '../data/dependence';
|
||||
import { Op } from 'sequelize';
|
||||
import config from '../config';
|
||||
import { CrontabViewModel, CronViewType } from '../data/cronView';
|
||||
import { initPosition } from '../data/env';
|
||||
@@ -18,9 +19,8 @@ import OpenService from '../services/open';
|
||||
import { shareStore } from '../shared/store';
|
||||
import Logger from './logger';
|
||||
import cronClient from '../schedule/client';
|
||||
import { TriggerHistory } from '../shared/triggerHistory';
|
||||
import { InstanceStatus, RunningInstanceModel } from '../data/runningInstance';
|
||||
import { setLang, systemLang } from '../shared/i18n';
|
||||
|
||||
export default async () => {
|
||||
const cronService = Container.get(CronService);
|
||||
const envService = Container.get(EnvService);
|
||||
@@ -28,17 +28,14 @@ export default async () => {
|
||||
const systemService = Container.get(SystemService);
|
||||
const userService = Container.get(UserService);
|
||||
const openService = Container.get(OpenService);
|
||||
|
||||
// 初始化增加系统配置
|
||||
await openService.initializeSystemApp();
|
||||
const [systemConfig] = await SystemModel.findOrCreate({
|
||||
where: { type: AuthDataType.systemConfig },
|
||||
const systemConfig = await SystemModel.getOrCreate({
|
||||
type: AuthDataType.systemConfig,
|
||||
});
|
||||
await SystemModel.findOrCreate({
|
||||
where: { type: AuthDataType.notification },
|
||||
});
|
||||
const [authConfig] = await SystemModel.findOrCreate({
|
||||
where: { type: AuthDataType.authConfig },
|
||||
await SystemModel.getOrCreate({ type: AuthDataType.notification });
|
||||
const authConfig = await SystemModel.getOrCreate({
|
||||
type: AuthDataType.authConfig,
|
||||
});
|
||||
if (!authConfig?.info || isDemoEnv()) {
|
||||
let authInfo = {
|
||||
@@ -54,36 +51,34 @@ export default async () => {
|
||||
} catch (error) {
|
||||
Logger.warn('Failed to read auth config file, using default credentials');
|
||||
}
|
||||
await SystemModel.upsert({
|
||||
id: authConfig?.id,
|
||||
await SystemModel.nativeUpdate(
|
||||
{ id: authConfig.id },
|
||||
{
|
||||
info: authInfo,
|
||||
type: AuthDataType.authConfig,
|
||||
});
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
const installDependencies = async () => {
|
||||
const docs = await DependenceModel.findAll({
|
||||
where: {},
|
||||
order: [
|
||||
const docs = await DependenceModel.find(
|
||||
{},
|
||||
{
|
||||
orderBy: orderBy([
|
||||
['type', 'DESC'],
|
||||
['createdAt', 'DESC'],
|
||||
],
|
||||
raw: true,
|
||||
});
|
||||
|
||||
await DependenceModel.update(
|
||||
]),
|
||||
},
|
||||
);
|
||||
await DependenceModel.nativeUpdate(
|
||||
{ id: docs.map((x) => x.id!) },
|
||||
{ status: DependenceStatus.queued, log: [] },
|
||||
{ where: { id: docs.map((x) => x.id!) } },
|
||||
);
|
||||
|
||||
setTimeout(async () => {
|
||||
await dependenceService.installDependenceOneByOne(docs);
|
||||
|
||||
const bootAfterLoader = await import('./bootAfter');
|
||||
bootAfterLoader.default();
|
||||
}, 5000);
|
||||
};
|
||||
|
||||
// 初始化更新 linux/python/nodejs 镜像源配置
|
||||
if (systemConfig.info?.pythonMirror) {
|
||||
systemService.updatePythonMirror({
|
||||
@@ -106,36 +101,40 @@ export default async () => {
|
||||
nodeMirror: systemConfig.info?.nodeMirror,
|
||||
});
|
||||
}
|
||||
|
||||
// 初始化新增默认全部任务视图
|
||||
CrontabViewModel.findAll({
|
||||
where: { type: CronViewType.系统, name: '全部任务' },
|
||||
raw: true,
|
||||
}).then((docs) => {
|
||||
CrontabViewModel.find({ type: CronViewType.系统, name: '全部任务' }, {}).then(
|
||||
(docs) => {
|
||||
if (docs.length === 0) {
|
||||
CrontabViewModel.create({
|
||||
CrontabViewModel.insert({
|
||||
name: '全部任务',
|
||||
type: CronViewType.系统,
|
||||
position: initPosition / 2,
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
const history = new TriggerHistory(CrontabModel.sequelize!);
|
||||
const pendingStops = await history.pendingStops();
|
||||
const pendingBatches = await history.pendingStopBatches();
|
||||
if (pendingStops.length || pendingBatches.length) await cronService.resumePendingStops(history, pendingStops, pendingBatches);
|
||||
await history.reconcileInstances();
|
||||
|
||||
},
|
||||
);
|
||||
// 初始化更新所有任务状态为空闲
|
||||
await CrontabModel.nativeUpdate({}, { status: CrontabStatus.idle });
|
||||
// 清空所有运行中的实例记录(服务重启后进程已不存在)
|
||||
await RunningInstanceModel.nativeUpdate(
|
||||
{ status: InstanceStatus.running },
|
||||
{
|
||||
status: InstanceStatus.stopped,
|
||||
finished_at: Math.floor(Date.now() / 1000),
|
||||
// The previous process's exit code cannot be recovered after a restart.
|
||||
},
|
||||
);
|
||||
// 初始化时执行一次所有的 ql repo 任务
|
||||
CrontabModel.findAll({
|
||||
where: {
|
||||
isDisabled: { [Op.ne]: 1 },
|
||||
command: {
|
||||
[Op.or]: [{ [Op.like]: `%ql repo%` }, { [Op.like]: `%ql raw%` }],
|
||||
CrontabModel.find(
|
||||
{
|
||||
isDisabled: { ['$ne']: 1 },
|
||||
$or: [
|
||||
...textSearch(['command'], 'ql repo').$or,
|
||||
...textSearch(['command'], 'ql raw').$or,
|
||||
],
|
||||
},
|
||||
},
|
||||
}).then((docs) => {
|
||||
{},
|
||||
).then((docs) => {
|
||||
for (let i = 0; i < docs.length; i++) {
|
||||
const doc = docs[i];
|
||||
if (doc) {
|
||||
@@ -143,88 +142,78 @@ export default async () => {
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// 更新2.11.3以前的脚本路径
|
||||
CrontabModel.findAll({
|
||||
where: {
|
||||
command: {
|
||||
[Op.or]: [
|
||||
{ [Op.like]: `%\/${config.rootPath}\/scripts\/%` },
|
||||
{ [Op.like]: `%\/${config.rootPath}\/config\/%` },
|
||||
{ [Op.like]: `%\/${config.rootPath}\/log\/%` },
|
||||
{ [Op.like]: `%\/${config.rootPath}\/db\/%` },
|
||||
],
|
||||
CrontabModel.find(
|
||||
{
|
||||
$or: ['scripts', 'config', 'log', 'db'].flatMap(
|
||||
(folder) =>
|
||||
textSearch(['command'], `/${config.rootPath}/${folder}/`).$or,
|
||||
),
|
||||
},
|
||||
},
|
||||
}).then(async (docs) => {
|
||||
{},
|
||||
).then(async (docs) => {
|
||||
for (let i = 0; i < docs.length; i++) {
|
||||
const doc = docs[i];
|
||||
if (doc) {
|
||||
if (doc.command.includes(`${config.rootPath}/scripts/`)) {
|
||||
await CrontabModel.update(
|
||||
await CrontabModel.nativeUpdate(
|
||||
{ id: doc.id },
|
||||
{ command: doc.command.replace(`${config.rootPath}/scripts/`, '') },
|
||||
{ where: { id: doc.id } },
|
||||
);
|
||||
}
|
||||
if (doc.command.includes(`${config.rootPath}/log/`)) {
|
||||
await CrontabModel.update(
|
||||
await CrontabModel.nativeUpdate(
|
||||
{ id: doc.id },
|
||||
{
|
||||
command: `${config.dataPath}/log/${doc.command.replace(
|
||||
`${config.rootPath}/log/`,
|
||||
'',
|
||||
)}`,
|
||||
},
|
||||
{ where: { id: doc.id } },
|
||||
);
|
||||
}
|
||||
if (doc.command.includes(`${config.rootPath}/config/`)) {
|
||||
await CrontabModel.update(
|
||||
await CrontabModel.nativeUpdate(
|
||||
{ id: doc.id },
|
||||
{
|
||||
command: `${config.dataPath}/config/${doc.command.replace(
|
||||
`${config.rootPath}/config/`,
|
||||
'',
|
||||
)}`,
|
||||
},
|
||||
{ where: { id: doc.id } },
|
||||
);
|
||||
}
|
||||
if (doc.command.includes(`${config.rootPath}/db/`)) {
|
||||
await CrontabModel.update(
|
||||
await CrontabModel.nativeUpdate(
|
||||
{ id: doc.id },
|
||||
{
|
||||
command: `${config.dataPath}/db/${doc.command.replace(
|
||||
`${config.rootPath}/db/`,
|
||||
'',
|
||||
)}`,
|
||||
},
|
||||
{ where: { id: doc.id } },
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// 初始化语言(必须在 autosave_crontab 之前)
|
||||
const lang = systemConfig.info?.lang || systemLang();
|
||||
setLang(lang);
|
||||
|
||||
// 确保 lang_env.sh 存在
|
||||
try {
|
||||
const langEnvExist = await fileExist(config.langEnvFile);
|
||||
if (!langEnvExist) {
|
||||
await writeFile(config.langEnvFile, `export QL_LANG='${lang}'\n`);
|
||||
}
|
||||
} catch { }
|
||||
|
||||
// Replace legacy task environment files before recovered tasks can run.
|
||||
await envService.set_envs();
|
||||
|
||||
} catch {}
|
||||
// 初始化保存一次ck和定时任务数据
|
||||
cronClient.readiness.configure(async () => {
|
||||
await cronService.autosave_crontab(true);
|
||||
await systemService.restoreCronConcurrency();
|
||||
});
|
||||
await cronClient.readiness.recover();
|
||||
|
||||
await envService.set_envs();
|
||||
const authInfo = await userService.getAuthInfo();
|
||||
await shareStore.updateAuthInfo(authInfo);
|
||||
await openService.refreshApps();
|
||||
|
||||
@@ -9,20 +9,17 @@ import { join } from 'path';
|
||||
import { t } from '../shared/i18n';
|
||||
import Logger from './logger';
|
||||
import { assertSubscriptionAlias } from '../shared/subscriptionPath';
|
||||
|
||||
export default async () => {
|
||||
const systemService = Container.get(SystemService);
|
||||
const scheduleService = Container.get(ScheduleService);
|
||||
const subscriptionService = Container.get(SubscriptionService);
|
||||
const sshKeyService = Container.get(SshKeyService);
|
||||
|
||||
// 生成内置token
|
||||
let tokenCommand = `ts-node-transpile-only ${join(
|
||||
config.rootPath,
|
||||
'back/token.ts',
|
||||
)}`;
|
||||
const tokenFile = join(config.rootPath, 'static/build/token.js');
|
||||
|
||||
if (await fileExist(tokenFile)) {
|
||||
tokenCommand = `node ${tokenFile}`;
|
||||
}
|
||||
@@ -41,7 +38,6 @@ export default async () => {
|
||||
},
|
||||
true,
|
||||
);
|
||||
|
||||
// 运行删除日志任务
|
||||
const data = await systemService.getSystemConfig();
|
||||
if (data && data.info) {
|
||||
@@ -61,20 +57,17 @@ export default async () => {
|
||||
true,
|
||||
);
|
||||
}
|
||||
|
||||
systemService.updateTimezone(data.info);
|
||||
|
||||
// Apply global SSH key if configured
|
||||
if (data.info.globalSshKey) {
|
||||
await sshKeyService.addGlobalSSHKey(data.info.globalSshKey, 'global');
|
||||
}
|
||||
}
|
||||
|
||||
await subscriptionService.setSshConfig();
|
||||
const subs = await subscriptionService.list();
|
||||
for (const sub of subs) {
|
||||
try {
|
||||
const doc = sub.get({ plain: true });
|
||||
const doc = sub;
|
||||
assertSubscriptionAlias(doc.alias);
|
||||
await subscriptionService.handleTask(doc, !sub.is_disabled);
|
||||
} catch (error) {
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
import type { RequestHandler } from 'express';
|
||||
import { t } from '../shared/i18n';
|
||||
|
||||
// Express 4 does not forward rejected async middleware promises itself.
|
||||
export function withAuthAvailability(handler: RequestHandler): RequestHandler {
|
||||
return (req, res, next) => {
|
||||
void Promise.resolve()
|
||||
.then(() => handler(req, res, next))
|
||||
.catch(() => {
|
||||
res.setHeader('Retry-After', '1');
|
||||
next(
|
||||
Object.assign(new Error(t('认证服务暂时不可用,请稍后重试')), {
|
||||
status: 503,
|
||||
}),
|
||||
);
|
||||
});
|
||||
};
|
||||
}
|
||||
@@ -1,14 +1,13 @@
|
||||
import { ErrorRequestHandler } from 'express';
|
||||
import { UniqueConstraintError } from 'sequelize';
|
||||
import { DatabaseError } from '../data/databaseErrors';
|
||||
import { t } from '../shared/i18n';
|
||||
|
||||
// Handle the database constraint itself so concurrent writes are covered too.
|
||||
const uniqueConstraintError: ErrorRequestHandler = (err, req, res, next) => {
|
||||
if (!(err instanceof UniqueConstraintError)) return next(err);
|
||||
if (!(err instanceof DatabaseError) || err.code !== 'UNIQUE_CONSTRAINT')
|
||||
return next(err);
|
||||
// Constraint details can contain environment values or application credentials.
|
||||
res
|
||||
.status(409)
|
||||
.json({ code: 409, message: t('资源已存在,请检查重复的名称或值') });
|
||||
};
|
||||
|
||||
export default uniqueConstraintError;
|
||||
|
||||
@@ -16,10 +16,6 @@ message ICron {
|
||||
string command = 3;
|
||||
repeated ISchedule extra_schedules = 4;
|
||||
string name = 5;
|
||||
optional uint32 max_queue_wait = 6;
|
||||
optional uint32 catchup_seconds = 7;
|
||||
optional int64 recovery_from = 8;
|
||||
optional bool skip_if_pending = 9;
|
||||
}
|
||||
|
||||
message AddCronRequest {
|
||||
|
||||
+2
-91
@@ -1,7 +1,7 @@
|
||||
// Code generated by protoc-gen-ts_proto. DO NOT EDIT.
|
||||
// versions:
|
||||
// protoc-gen-ts_proto v2.6.1
|
||||
// protoc v5.29.0
|
||||
// protoc v5.28.3
|
||||
// source: back/protos/cron.proto
|
||||
|
||||
/* eslint-disable */
|
||||
@@ -31,10 +31,6 @@ export interface ICron {
|
||||
command: string;
|
||||
extra_schedules: ISchedule[];
|
||||
name: string;
|
||||
max_queue_wait?: number | undefined;
|
||||
catchup_seconds?: number | undefined;
|
||||
recovery_from?: number | undefined;
|
||||
skip_if_pending?: boolean | undefined;
|
||||
}
|
||||
|
||||
export interface AddCronRequest {
|
||||
@@ -116,17 +112,7 @@ export const ISchedule: MessageFns<ISchedule> = {
|
||||
};
|
||||
|
||||
function createBaseICron(): ICron {
|
||||
return {
|
||||
id: "",
|
||||
schedule: "",
|
||||
command: "",
|
||||
extra_schedules: [],
|
||||
name: "",
|
||||
max_queue_wait: undefined,
|
||||
catchup_seconds: undefined,
|
||||
recovery_from: undefined,
|
||||
skip_if_pending: undefined,
|
||||
};
|
||||
return { id: "", schedule: "", command: "", extra_schedules: [], name: "" };
|
||||
}
|
||||
|
||||
export const ICron: MessageFns<ICron> = {
|
||||
@@ -146,18 +132,6 @@ export const ICron: MessageFns<ICron> = {
|
||||
if (message.name !== "") {
|
||||
writer.uint32(42).string(message.name);
|
||||
}
|
||||
if (message.max_queue_wait !== undefined) {
|
||||
writer.uint32(48).uint32(message.max_queue_wait);
|
||||
}
|
||||
if (message.catchup_seconds !== undefined) {
|
||||
writer.uint32(56).uint32(message.catchup_seconds);
|
||||
}
|
||||
if (message.recovery_from !== undefined) {
|
||||
writer.uint32(64).int64(message.recovery_from);
|
||||
}
|
||||
if (message.skip_if_pending !== undefined) {
|
||||
writer.uint32(72).bool(message.skip_if_pending);
|
||||
}
|
||||
return writer;
|
||||
},
|
||||
|
||||
@@ -208,38 +182,6 @@ export const ICron: MessageFns<ICron> = {
|
||||
message.name = reader.string();
|
||||
continue;
|
||||
}
|
||||
case 6: {
|
||||
if (tag !== 48) {
|
||||
break;
|
||||
}
|
||||
|
||||
message.max_queue_wait = reader.uint32();
|
||||
continue;
|
||||
}
|
||||
case 7: {
|
||||
if (tag !== 56) {
|
||||
break;
|
||||
}
|
||||
|
||||
message.catchup_seconds = reader.uint32();
|
||||
continue;
|
||||
}
|
||||
case 8: {
|
||||
if (tag !== 64) {
|
||||
break;
|
||||
}
|
||||
|
||||
message.recovery_from = longToNumber(reader.int64());
|
||||
continue;
|
||||
}
|
||||
case 9: {
|
||||
if (tag !== 72) {
|
||||
break;
|
||||
}
|
||||
|
||||
message.skip_if_pending = reader.bool();
|
||||
continue;
|
||||
}
|
||||
}
|
||||
if ((tag & 7) === 4 || tag === 0) {
|
||||
break;
|
||||
@@ -258,10 +200,6 @@ export const ICron: MessageFns<ICron> = {
|
||||
? object.extra_schedules.map((e: any) => ISchedule.fromJSON(e))
|
||||
: [],
|
||||
name: isSet(object.name) ? globalThis.String(object.name) : "",
|
||||
max_queue_wait: isSet(object.max_queue_wait) ? globalThis.Number(object.max_queue_wait) : undefined,
|
||||
catchup_seconds: isSet(object.catchup_seconds) ? globalThis.Number(object.catchup_seconds) : undefined,
|
||||
recovery_from: isSet(object.recovery_from) ? globalThis.Number(object.recovery_from) : undefined,
|
||||
skip_if_pending: isSet(object.skip_if_pending) ? globalThis.Boolean(object.skip_if_pending) : undefined,
|
||||
};
|
||||
},
|
||||
|
||||
@@ -282,18 +220,6 @@ export const ICron: MessageFns<ICron> = {
|
||||
if (message.name !== "") {
|
||||
obj.name = message.name;
|
||||
}
|
||||
if (message.max_queue_wait !== undefined) {
|
||||
obj.max_queue_wait = Math.round(message.max_queue_wait);
|
||||
}
|
||||
if (message.catchup_seconds !== undefined) {
|
||||
obj.catchup_seconds = Math.round(message.catchup_seconds);
|
||||
}
|
||||
if (message.recovery_from !== undefined) {
|
||||
obj.recovery_from = Math.round(message.recovery_from);
|
||||
}
|
||||
if (message.skip_if_pending !== undefined) {
|
||||
obj.skip_if_pending = message.skip_if_pending;
|
||||
}
|
||||
return obj;
|
||||
},
|
||||
|
||||
@@ -307,10 +233,6 @@ export const ICron: MessageFns<ICron> = {
|
||||
message.command = object.command ?? "";
|
||||
message.extra_schedules = object.extra_schedules?.map((e) => ISchedule.fromPartial(e)) || [];
|
||||
message.name = object.name ?? "";
|
||||
message.max_queue_wait = object.max_queue_wait ?? undefined;
|
||||
message.catchup_seconds = object.catchup_seconds ?? undefined;
|
||||
message.recovery_from = object.recovery_from ?? undefined;
|
||||
message.skip_if_pending = object.skip_if_pending ?? undefined;
|
||||
return message;
|
||||
},
|
||||
};
|
||||
@@ -696,17 +618,6 @@ type KeysOfUnion<T> = T extends T ? keyof T : never;
|
||||
export type Exact<P, I extends P> = P extends Builtin ? P
|
||||
: P & { [K in keyof P]: Exact<P[K], I[K]> } & { [K in Exclude<keyof I, KeysOfUnion<P>>]: never };
|
||||
|
||||
function longToNumber(int64: { toString(): string }): number {
|
||||
const num = globalThis.Number(int64.toString());
|
||||
if (num > globalThis.Number.MAX_SAFE_INTEGER) {
|
||||
throw new globalThis.Error("Value is larger than Number.MAX_SAFE_INTEGER");
|
||||
}
|
||||
if (num < globalThis.Number.MIN_SAFE_INTEGER) {
|
||||
throw new globalThis.Error("Value is smaller than Number.MIN_SAFE_INTEGER");
|
||||
}
|
||||
return num;
|
||||
}
|
||||
|
||||
function isSet(value: any): boolean {
|
||||
return value !== null && value !== undefined;
|
||||
}
|
||||
|
||||
+14
-45
@@ -3,8 +3,6 @@ import { AddCronRequest, AddCronResponse } from '../protos/cron';
|
||||
import { createCronJob, CronJob } from '../shared/cronScheduler';
|
||||
import { isValidCronSchedule } from '../shared/cronSchedule';
|
||||
import { scheduleStacks } from './data';
|
||||
import { latestMissedSlot } from '../shared/cronRecovery';
|
||||
import { slotId } from '../shared/triggerHistory';
|
||||
import { runCron } from '../shared/runCron';
|
||||
import Logger from '../loaders/logger';
|
||||
import { t, tf } from '../shared/i18n';
|
||||
@@ -14,12 +12,9 @@ const isValidCronField = (cron: string): boolean => {
|
||||
return isValidCronSchedule(cron);
|
||||
};
|
||||
|
||||
const definitions = new WeakMap<CronJob[], string>();
|
||||
|
||||
const addCron = (
|
||||
call: ServerUnaryCall<AddCronRequest, AddCronResponse>,
|
||||
callback: sendUnaryData<AddCronResponse>,
|
||||
savePlan?: () => Promise<void>,
|
||||
) => {
|
||||
// ===== 第一遍:预校验所有 cron 表达式 =====
|
||||
const validationErrors: string[] = [];
|
||||
@@ -59,41 +54,26 @@ const addCron = (
|
||||
|
||||
// Prepare stopped jobs first: construction errors must preserve the old snapshot.
|
||||
const prepared = new Map<string, CronJob[]>();
|
||||
const desired = new Map(call.request.crons.map((item) => [item.id, item]));
|
||||
const recoveries: (() => Promise<void>)[] = [];
|
||||
try {
|
||||
for (const item of desired.values()) {
|
||||
const signature = JSON.stringify([item.schedule, item.command,
|
||||
(item.extra_schedules || []).map((s) => s.schedule), item.max_queue_wait || 0,
|
||||
!!item.skip_if_pending, item.catchup_seconds || 0, item.catchup_seconds || item.skip_if_pending ? item.recovery_from : 0]);
|
||||
const current = scheduleStacks.get(item.id);
|
||||
if (current && definitions.get(current) === signature) continue;
|
||||
for (const item of call.request.crons) {
|
||||
const jobs: CronJob[] = [];
|
||||
definitions.set(jobs, signature);
|
||||
prepared.get(item.id)?.forEach((job) => job.cancel());
|
||||
prepared.set(item.id, jobs);
|
||||
for (const [ruleIndex, schedule] of [
|
||||
for (const schedule of [
|
||||
item.schedule,
|
||||
...(item.extra_schedules || []).map((x) => x.schedule),
|
||||
].entries()) {
|
||||
const fire = async (date: Date, source: 'node' | 'recovery' = 'node') => {
|
||||
const isCurrent = () => scheduleStacks.get(item.id) === jobs;
|
||||
if (!isCurrent()) return;
|
||||
await runCron(item.command, item, isCurrent, date && {
|
||||
id: slotId(item.id, ruleIndex, schedule, +date), time: +date, source,
|
||||
});
|
||||
};
|
||||
if (call.request.replace && item.catchup_seconds && item.recovery_from) {
|
||||
recoveries.push(async () => {
|
||||
const now = Date.now();
|
||||
const since = Math.max(item.recovery_from!, now - item.catchup_seconds! * 1000);
|
||||
const time = latestMissedSlot(schedule, since, now);
|
||||
if (time !== null) await fire(new Date(time), 'recovery');
|
||||
});
|
||||
}
|
||||
]) {
|
||||
jobs.push(
|
||||
createCronJob(
|
||||
schedule,
|
||||
fire,
|
||||
async () => {
|
||||
Logger.info(t('[schedule][准备运行任务] 命令: %s'), item.command);
|
||||
await runCron(
|
||||
item.command,
|
||||
item,
|
||||
() => scheduleStacks.get(item.id) === jobs,
|
||||
);
|
||||
},
|
||||
{
|
||||
name: `${item.id}: ${item.name || ''}`,
|
||||
logger: Logger,
|
||||
@@ -114,13 +94,10 @@ const addCron = (
|
||||
return;
|
||||
}
|
||||
|
||||
const activate = () => {
|
||||
if (call.request.replace) {
|
||||
for (const [id, jobs] of scheduleStacks) {
|
||||
if (desired.has(id)) continue;
|
||||
for (const jobs of scheduleStacks.values())
|
||||
jobs.forEach((job) => job?.cancel());
|
||||
scheduleStacks.delete(id);
|
||||
}
|
||||
scheduleStacks.clear();
|
||||
}
|
||||
for (const [id, jobs] of prepared) {
|
||||
scheduleStacks.get(id)?.forEach((job) => job.cancel());
|
||||
@@ -134,14 +111,6 @@ const addCron = (
|
||||
}
|
||||
|
||||
callback(null, null);
|
||||
for (const recover of recoveries) setImmediate(() => recover().catch((err) => Logger.error(String(err))));
|
||||
};
|
||||
if (savePlan) {
|
||||
savePlan().then(activate).catch(error => {
|
||||
for (const jobs of prepared.values()) jobs.forEach(job => job.cancel());
|
||||
callback(error);
|
||||
});
|
||||
} else activate();
|
||||
};
|
||||
|
||||
export { addCron };
|
||||
|
||||
+1
-39
@@ -39,10 +39,7 @@ import {
|
||||
RunCronsRequest,
|
||||
} from '../protos/api';
|
||||
import { NotificationInfo } from '../data/notify';
|
||||
import { Model } from 'sequelize';
|
||||
|
||||
Container.set('logger', LoggerInstance);
|
||||
|
||||
export const getEnvs = async (
|
||||
call: ServerUnaryCall<GetEnvsRequest, EnvsResponse>,
|
||||
callback: sendUnaryData<EnvsResponse>,
|
||||
@@ -62,7 +59,6 @@ export const getEnvs = async (
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
export const createEnv = async (
|
||||
call: ServerUnaryCall<CreateEnvRequest, EnvsResponse>,
|
||||
callback: sendUnaryData<EnvsResponse>,
|
||||
@@ -75,7 +71,6 @@ export const createEnv = async (
|
||||
callback(e);
|
||||
}
|
||||
};
|
||||
|
||||
export const updateEnv = async (
|
||||
call: ServerUnaryCall<UpdateEnvRequest, EnvResponse>,
|
||||
callback: sendUnaryData<EnvResponse>,
|
||||
@@ -88,7 +83,6 @@ export const updateEnv = async (
|
||||
message: 'id parameter is required',
|
||||
});
|
||||
}
|
||||
|
||||
const envService = Container.get(EnvService);
|
||||
const data = await envService.update(
|
||||
pick(call.request.env, ['id', 'name', 'value', 'remarks']) as EnvItem,
|
||||
@@ -98,7 +92,6 @@ export const updateEnv = async (
|
||||
callback(e);
|
||||
}
|
||||
};
|
||||
|
||||
export const deleteEnvs = async (
|
||||
call: ServerUnaryCall<DeleteEnvsRequest, Response>,
|
||||
callback: sendUnaryData<Response>,
|
||||
@@ -110,7 +103,6 @@ export const deleteEnvs = async (
|
||||
message: 'ids parameter is required',
|
||||
});
|
||||
}
|
||||
|
||||
const envService = Container.get(EnvService);
|
||||
await envService.remove(call.request.ids);
|
||||
callback(null, { code: 200 });
|
||||
@@ -118,7 +110,6 @@ export const deleteEnvs = async (
|
||||
callback(e);
|
||||
}
|
||||
};
|
||||
|
||||
export const moveEnv = async (
|
||||
call: ServerUnaryCall<MoveEnvRequest, EnvResponse>,
|
||||
callback: sendUnaryData<EnvResponse>,
|
||||
@@ -131,7 +122,6 @@ export const moveEnv = async (
|
||||
message: 'id parameter is required',
|
||||
});
|
||||
}
|
||||
|
||||
const envService = Container.get(EnvService);
|
||||
const data = await envService.move(call.request.id, {
|
||||
fromIndex: call.request.fromIndex,
|
||||
@@ -142,7 +132,6 @@ export const moveEnv = async (
|
||||
callback(e);
|
||||
}
|
||||
};
|
||||
|
||||
export const disableEnvs = async (
|
||||
call: ServerUnaryCall<DisableEnvsRequest, Response>,
|
||||
callback: sendUnaryData<Response>,
|
||||
@@ -154,7 +143,6 @@ export const disableEnvs = async (
|
||||
message: 'ids parameter is required',
|
||||
});
|
||||
}
|
||||
|
||||
const envService = Container.get(EnvService);
|
||||
await envService.disabled(call.request.ids);
|
||||
callback(null, { code: 200 });
|
||||
@@ -162,7 +150,6 @@ export const disableEnvs = async (
|
||||
callback(e);
|
||||
}
|
||||
};
|
||||
|
||||
export const enableEnvs = async (
|
||||
call: ServerUnaryCall<EnableEnvsRequest, Response>,
|
||||
callback: sendUnaryData<Response>,
|
||||
@@ -174,7 +161,6 @@ export const enableEnvs = async (
|
||||
message: 'ids parameter is required',
|
||||
});
|
||||
}
|
||||
|
||||
const envService = Container.get(EnvService);
|
||||
await envService.enabled(call.request.ids);
|
||||
callback(null, { code: 200 });
|
||||
@@ -182,7 +168,6 @@ export const enableEnvs = async (
|
||||
callback(e);
|
||||
}
|
||||
};
|
||||
|
||||
export const updateEnvNames = async (
|
||||
call: ServerUnaryCall<UpdateEnvNamesRequest, Response>,
|
||||
callback: sendUnaryData<Response>,
|
||||
@@ -194,7 +179,6 @@ export const updateEnvNames = async (
|
||||
message: 'ids parameter is required',
|
||||
});
|
||||
}
|
||||
|
||||
const envService = Container.get(EnvService);
|
||||
await envService.updateNames({
|
||||
ids: call.request.ids,
|
||||
@@ -205,7 +189,6 @@ export const updateEnvNames = async (
|
||||
callback(e);
|
||||
}
|
||||
};
|
||||
|
||||
export const getEnvById = async (
|
||||
call: ServerUnaryCall<GetEnvByIdRequest, EnvResponse>,
|
||||
callback: sendUnaryData<EnvResponse>,
|
||||
@@ -218,7 +201,6 @@ export const getEnvById = async (
|
||||
message: 'id parameter is required',
|
||||
});
|
||||
}
|
||||
|
||||
const envService = Container.get(EnvService);
|
||||
const data = await envService.getDb({ id: call.request.id });
|
||||
callback(null, {
|
||||
@@ -229,7 +211,6 @@ export const getEnvById = async (
|
||||
callback(e);
|
||||
}
|
||||
};
|
||||
|
||||
export const systemNotify = async (
|
||||
call: ServerUnaryCall<SystemNotifyRequest, Response>,
|
||||
callback: sendUnaryData<Response>,
|
||||
@@ -247,7 +228,6 @@ export const systemNotify = async (
|
||||
callback(e);
|
||||
}
|
||||
};
|
||||
|
||||
export const recordNotifyLog = async (
|
||||
call: ServerUnaryCall<RecordNotifyLogRequest, Response>,
|
||||
callback: sendUnaryData<Response>,
|
||||
@@ -267,12 +247,9 @@ export const recordNotifyLog = async (
|
||||
callback(error);
|
||||
}
|
||||
};
|
||||
|
||||
const normalizeCronData = (data: CronItem | null): CronItem | undefined => {
|
||||
if (!data) return undefined;
|
||||
// create() returns a Sequelize instance; spreading it omits attribute getters.
|
||||
const cron =
|
||||
data instanceof Model ? (data.get({ plain: true }) as CronItem) : data;
|
||||
const cron = data;
|
||||
return {
|
||||
...cron,
|
||||
labels: cron.labels ?? [],
|
||||
@@ -283,7 +260,6 @@ const normalizeCronData = (data: CronItem | null): CronItem | undefined => {
|
||||
task_after: cron.task_after ?? undefined,
|
||||
};
|
||||
};
|
||||
|
||||
export const getCronDetail = async (
|
||||
call: ServerUnaryCall<CronDetailRequest, CronDetailResponse>,
|
||||
callback: sendUnaryData<CronDetailResponse>,
|
||||
@@ -305,7 +281,6 @@ export const getCronDetail = async (
|
||||
callback(e);
|
||||
}
|
||||
};
|
||||
|
||||
export const createCron = async (
|
||||
call: ServerUnaryCall<CreateCronRequest, CronResponse>,
|
||||
callback: sendUnaryData<CronResponse>,
|
||||
@@ -318,7 +293,6 @@ export const createCron = async (
|
||||
callback(e);
|
||||
}
|
||||
};
|
||||
|
||||
export const updateCron = async (
|
||||
call: ServerUnaryCall<UpdateCronRequest, CronResponse>,
|
||||
callback: sendUnaryData<CronResponse>,
|
||||
@@ -326,7 +300,6 @@ export const updateCron = async (
|
||||
try {
|
||||
const cronService = Container.get(CronService);
|
||||
const { id, ...fields } = call.request;
|
||||
|
||||
const updateRequest = {
|
||||
id,
|
||||
...Object.entries(fields).reduce((acc: any, [key, value]) => {
|
||||
@@ -336,14 +309,12 @@ export const updateCron = async (
|
||||
return acc;
|
||||
}, {}),
|
||||
} as UpdateCronRequest;
|
||||
|
||||
const data = (await cronService.update(updateRequest)) as CronItem;
|
||||
callback(null, { code: 200, data: normalizeCronData(data) });
|
||||
} catch (e: any) {
|
||||
callback(e);
|
||||
}
|
||||
};
|
||||
|
||||
export const deleteCrons = async (
|
||||
call: ServerUnaryCall<DeleteCronsRequest, Response>,
|
||||
callback: sendUnaryData<Response>,
|
||||
@@ -356,7 +327,6 @@ export const deleteCrons = async (
|
||||
callback(e);
|
||||
}
|
||||
};
|
||||
|
||||
export const getCrons = async (
|
||||
call: ServerUnaryCall<GetCronsRequest, CronsResponse>,
|
||||
callback: sendUnaryData<CronsResponse>,
|
||||
@@ -384,7 +354,6 @@ export const getCrons = async (
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
export const getCronById = async (
|
||||
call: ServerUnaryCall<GetCronByIdRequest, CronResponse>,
|
||||
callback: sendUnaryData<CronResponse>,
|
||||
@@ -397,7 +366,6 @@ export const getCronById = async (
|
||||
message: 'id parameter is required',
|
||||
});
|
||||
}
|
||||
|
||||
const cronService = Container.get(CronService);
|
||||
const data = (await cronService.getDb({ id: call.request.id })) as CronItem;
|
||||
callback(null, { code: 200, data: normalizeCronData(data) });
|
||||
@@ -409,7 +377,6 @@ export const getCronById = async (
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
export const enableCrons = async (
|
||||
call: ServerUnaryCall<EnableCronsRequest, Response>,
|
||||
callback: sendUnaryData<Response>,
|
||||
@@ -421,7 +388,6 @@ export const enableCrons = async (
|
||||
message: 'ids parameter is required',
|
||||
});
|
||||
}
|
||||
|
||||
const cronService = Container.get(CronService);
|
||||
await cronService.enabled(call.request.ids);
|
||||
callback(null, { code: 200 });
|
||||
@@ -429,7 +395,6 @@ export const enableCrons = async (
|
||||
callback(e);
|
||||
}
|
||||
};
|
||||
|
||||
export const disableCrons = async (
|
||||
call: ServerUnaryCall<DisableCronsRequest, Response>,
|
||||
callback: sendUnaryData<Response>,
|
||||
@@ -441,7 +406,6 @@ export const disableCrons = async (
|
||||
message: 'ids parameter is required',
|
||||
});
|
||||
}
|
||||
|
||||
const cronService = Container.get(CronService);
|
||||
await cronService.disabled(call.request.ids);
|
||||
callback(null, { code: 200 });
|
||||
@@ -449,7 +413,6 @@ export const disableCrons = async (
|
||||
callback(e);
|
||||
}
|
||||
};
|
||||
|
||||
export const runCrons = async (
|
||||
call: ServerUnaryCall<RunCronsRequest, Response>,
|
||||
callback: sendUnaryData<Response>,
|
||||
@@ -461,7 +424,6 @@ export const runCrons = async (
|
||||
message: 'ids parameter is required',
|
||||
});
|
||||
}
|
||||
|
||||
const cronService = Container.get(CronService);
|
||||
await cronService.run(call.request.ids);
|
||||
callback(null, { code: 200 });
|
||||
|
||||
@@ -94,7 +94,7 @@ class Client {
|
||||
const registrationTimeoutMs = Math.min(120000, 5000 + ruleCount * 5);
|
||||
return new Promise((resolve, reject) => {
|
||||
this.client.addCron(
|
||||
AddCronRequest.fromPartial({ crons: request, replace }),
|
||||
{ crons: request, replace },
|
||||
new Metadata(),
|
||||
{ deadline: Date.now() + registrationTimeoutMs },
|
||||
(err, res) => {
|
||||
|
||||
@@ -4,6 +4,7 @@ import path from 'path';
|
||||
import { request } from 'undici';
|
||||
import { HealthCheckRequest, HealthCheckResponse } from '../protos/health';
|
||||
import config from '../config';
|
||||
import { database } from '../data';
|
||||
|
||||
function formatError(error: unknown): string {
|
||||
if (!(error instanceof Error)) {
|
||||
@@ -54,7 +55,7 @@ const check = async (
|
||||
switch (call.request.service) {
|
||||
// Local scheduler liveness only: never call HTTP from this probe.
|
||||
case 'scheduler':
|
||||
return callback(null, { status: 1 });
|
||||
return callback(null, { status: database.healthy ? 1 : 2 });
|
||||
case 'cron': {
|
||||
const healthUrl = `http://localhost:${config.port}${
|
||||
config.baseUrl || ''
|
||||
|
||||
@@ -1,59 +0,0 @@
|
||||
import { ServerUnaryCall, sendUnaryData } from '@grpc/grpc-js';
|
||||
import {
|
||||
AddCronRequest,
|
||||
AddCronResponse,
|
||||
DeleteCronRequest,
|
||||
DeleteCronResponse,
|
||||
} from '../protos/cron';
|
||||
import { addCron } from './addCron';
|
||||
import { delCron } from './delCron';
|
||||
import { randomUUID } from 'crypto';
|
||||
import { saveSchedulePlan, confirmSchedulePlan } from '../shared/scheduleAudit';
|
||||
|
||||
// Keep acknowledgement, publication and timer replacement in request order,
|
||||
// even if the client times out and sends a replacement snapshot.
|
||||
let pending = Promise.resolve();
|
||||
function serialize(action: () => Promise<void>) {
|
||||
pending = pending.then(action, action);
|
||||
return pending;
|
||||
}
|
||||
|
||||
export function registeredAdd(
|
||||
call: ServerUnaryCall<AddCronRequest, AddCronResponse>,
|
||||
callback: sendUnaryData<AddCronResponse>,
|
||||
) {
|
||||
return serialize(async () => {
|
||||
const db = require('../data').sequelize;
|
||||
const token = randomUUID();
|
||||
let first = 0;
|
||||
const last = await new Promise<number>((resolve, reject) => {
|
||||
addCron(
|
||||
call,
|
||||
(error) => (error ? reject(error) : resolve(Date.now())),
|
||||
async () => {
|
||||
await saveSchedulePlan(db, call.request, undefined, token);
|
||||
first = Date.now();
|
||||
},
|
||||
);
|
||||
});
|
||||
await confirmSchedulePlan(db, token, first, last, call.request.replace);
|
||||
callback(null, null);
|
||||
}).catch((error) => callback(error));
|
||||
}
|
||||
|
||||
export function registeredDelete(
|
||||
call: ServerUnaryCall<DeleteCronRequest, DeleteCronResponse>,
|
||||
callback: sendUnaryData<DeleteCronResponse>,
|
||||
) {
|
||||
return serialize(async () => {
|
||||
const db = require('../data').sequelize;
|
||||
const token = randomUUID();
|
||||
await saveSchedulePlan(db, call.request, undefined, token);
|
||||
const first = Date.now();
|
||||
delCron(call, (error) => {
|
||||
if (error) throw error;
|
||||
});
|
||||
await confirmSchedulePlan(db, token, first, Date.now(), false);
|
||||
callback(null, null);
|
||||
}).catch((error) => callback(error));
|
||||
}
|
||||
+411
-787
File diff suppressed because it is too large
Load Diff
+19
-31
@@ -1,3 +1,4 @@
|
||||
import { Query, QuerySpec, orderBy } from '../data/queries';
|
||||
import { Service, Inject } from 'typedi';
|
||||
import winston from 'winston';
|
||||
import { CrontabView, CrontabViewModel } from '../data/cronView';
|
||||
@@ -7,12 +8,12 @@ import {
|
||||
minPosition,
|
||||
stepPosition,
|
||||
} from '../data/env';
|
||||
import { FindOptions } from 'sequelize';
|
||||
|
||||
@Service()
|
||||
export default class CronViewService {
|
||||
constructor(@Inject('logger') private logger: winston.Logger) {}
|
||||
|
||||
constructor(
|
||||
@Inject('logger')
|
||||
private logger: winston.Logger,
|
||||
) {}
|
||||
public async create(payload: CrontabView): Promise<CrontabView> {
|
||||
let position = initPosition;
|
||||
const views = await this.list();
|
||||
@@ -22,61 +23,51 @@ export default class CronViewService {
|
||||
position = position / 2;
|
||||
const tab = new CrontabView({ ...payload, position });
|
||||
const doc = await this.insert(tab);
|
||||
|
||||
await this.checkPosition(tab.position!);
|
||||
return doc;
|
||||
}
|
||||
|
||||
public async insert(payload: CrontabView): Promise<CrontabView> {
|
||||
return await CrontabViewModel.create(payload, { returning: true });
|
||||
return await CrontabViewModel.insert(payload);
|
||||
}
|
||||
|
||||
public async update(payload: CrontabView): Promise<CrontabView> {
|
||||
const doc = await this.getDb({ id: payload.id });
|
||||
const tab = new CrontabView({ ...doc, ...payload });
|
||||
const newDoc = await this.updateDb(tab);
|
||||
return newDoc;
|
||||
}
|
||||
|
||||
public async updateDb(payload: CrontabView): Promise<CrontabView> {
|
||||
await CrontabViewModel.update(payload, { where: { id: payload.id } });
|
||||
await CrontabViewModel.nativeUpdate({ id: payload.id }, payload);
|
||||
return await this.getDb({ id: payload.id });
|
||||
}
|
||||
|
||||
public async remove(ids: number[]) {
|
||||
await CrontabViewModel.destroy({ where: { id: ids } });
|
||||
await CrontabViewModel.nativeDelete({ id: ids });
|
||||
}
|
||||
|
||||
public async list(): Promise<CrontabView[]> {
|
||||
try {
|
||||
const result = await CrontabViewModel.findAll({
|
||||
where: {},
|
||||
order: [['position', 'DESC']],
|
||||
});
|
||||
const result = await CrontabViewModel.find(
|
||||
{},
|
||||
{
|
||||
orderBy: orderBy([['position', 'DESC']]),
|
||||
},
|
||||
);
|
||||
return result;
|
||||
} catch (error) {
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
public async getDb(
|
||||
query: FindOptions<CrontabView>['where'],
|
||||
): Promise<CrontabView> {
|
||||
const doc: any = await CrontabViewModel.findOne({ where: { ...query } });
|
||||
public async getDb(query: QuerySpec['where']): Promise<CrontabView> {
|
||||
const doc: any = await CrontabViewModel.findOne({ ...query }, {});
|
||||
if (!doc) {
|
||||
throw new Error(`CronView ${JSON.stringify(query)} not found`);
|
||||
}
|
||||
return doc.get({ plain: true });
|
||||
return doc;
|
||||
}
|
||||
|
||||
public async disabled(ids: number[]) {
|
||||
await CrontabViewModel.update({ isDisabled: 1 }, { where: { id: ids } });
|
||||
await CrontabViewModel.nativeUpdate({ id: ids }, { isDisabled: 1 });
|
||||
}
|
||||
|
||||
public async enabled(ids: number[]) {
|
||||
await CrontabViewModel.update({ isDisabled: 0 }, { where: { id: ids } });
|
||||
await CrontabViewModel.nativeUpdate({ id: ids }, { isDisabled: 0 });
|
||||
}
|
||||
|
||||
private async checkPosition(position: number) {
|
||||
const precisionPosition = parseFloat(position.toPrecision(16));
|
||||
if (precisionPosition < minPosition || precisionPosition > maxPosition) {
|
||||
@@ -88,11 +79,9 @@ export default class CronViewService {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private getPrecisionPosition(position: number): number {
|
||||
return parseFloat(position.toPrecision(16));
|
||||
}
|
||||
|
||||
public async move({
|
||||
id,
|
||||
fromIndex,
|
||||
@@ -118,7 +107,6 @@ export default class CronViewService {
|
||||
id,
|
||||
position: this.getPrecisionPosition(targetPosition),
|
||||
});
|
||||
|
||||
await this.checkPosition(targetPosition);
|
||||
return newDoc;
|
||||
}
|
||||
|
||||
+64
-166
@@ -1,3 +1,5 @@
|
||||
import { textSearch } from '../data/queries';
|
||||
import { Query, QuerySpec, orderBy } from '../data/queries';
|
||||
import { Service, Inject } from 'typedi';
|
||||
import winston from 'winston';
|
||||
import config from '../config';
|
||||
@@ -10,7 +12,6 @@ import {
|
||||
} from '../data/dependence';
|
||||
import { spawn } from 'cross-spawn';
|
||||
import SockService from './sock';
|
||||
import { FindOptions, Op } from 'sequelize';
|
||||
import {
|
||||
fileExist,
|
||||
getPid,
|
||||
@@ -27,25 +28,13 @@ import taskLimit from '../shared/pLimit';
|
||||
import { detectOS } from '../config/util';
|
||||
import { LINUX_DEPENDENCE_COMMAND } from '../config/const';
|
||||
import { t, tf } from '../shared/i18n';
|
||||
import { randomUUID } from 'crypto';
|
||||
|
||||
type RefreshType = 'nodejs' | 'python3';
|
||||
type RefreshJob = {
|
||||
id: string;
|
||||
type: RefreshType;
|
||||
state: 'running' | 'completed' | 'failed';
|
||||
};
|
||||
|
||||
@Service()
|
||||
export default class DependenceService {
|
||||
private activeRefreshJob?: RefreshJob;
|
||||
private refreshJobs = new Map<string, RefreshJob>();
|
||||
|
||||
constructor(
|
||||
@Inject('logger') private logger: winston.Logger,
|
||||
@Inject('logger')
|
||||
private logger: winston.Logger,
|
||||
private sockService: SockService,
|
||||
) {}
|
||||
|
||||
public async create(payloads: Dependence[]): Promise<Dependence[]> {
|
||||
const tabs = payloads.map((x) => {
|
||||
getInstallCommand(x.type, x.name);
|
||||
@@ -56,14 +45,14 @@ export default class DependenceService {
|
||||
this.installDependenceOneByOne(docs);
|
||||
return docs;
|
||||
}
|
||||
|
||||
public async insert(payloads: Dependence[]): Promise<Dependence[]> {
|
||||
const docs = await DependenceModel.bulkCreate(payloads);
|
||||
const docs = await DependenceModel.insertMany(payloads);
|
||||
return docs;
|
||||
}
|
||||
|
||||
public async update(
|
||||
payload: Dependence & { id: string },
|
||||
payload: Dependence & {
|
||||
id: string;
|
||||
},
|
||||
): Promise<Dependence> {
|
||||
const { id, ...other } = payload;
|
||||
const doc = await this.getDb({ id });
|
||||
@@ -77,14 +66,12 @@ export default class DependenceService {
|
||||
this.installDependenceOneByOne([newDoc]);
|
||||
return newDoc;
|
||||
}
|
||||
|
||||
private async updateDb(payload: Dependence): Promise<Dependence> {
|
||||
await DependenceModel.update(payload, { where: { id: payload.id } });
|
||||
await DependenceModel.nativeUpdate({ id: payload.id }, payload);
|
||||
return await this.getDb({ id: payload.id });
|
||||
}
|
||||
|
||||
public async remove(ids: number[], force = false): Promise<Dependence[]> {
|
||||
const docs = await DependenceModel.findAll({ where: { id: ids } });
|
||||
const docs = await DependenceModel.find({ id: ids }, {});
|
||||
for (const doc of docs) {
|
||||
taskLimit.removeQueuedDependency(doc);
|
||||
}
|
||||
@@ -99,22 +86,18 @@ export default class DependenceService {
|
||||
);
|
||||
const unInstalledDeps = docs.filter((x) => !installedDeps.includes(x));
|
||||
await this.removeDb(unInstalledDeps.map((x) => x.id!));
|
||||
|
||||
if (installedDeps.length) {
|
||||
await DependenceModel.update(
|
||||
await DependenceModel.nativeUpdate(
|
||||
{ id: installedDeps.map((x) => x.id!) },
|
||||
{ status: DependenceStatus.queued, log: [] },
|
||||
{ where: { id: installedDeps.map((x) => x.id!) } },
|
||||
);
|
||||
|
||||
this.installDependenceOneByOne(installedDeps, false, force);
|
||||
}
|
||||
return docs;
|
||||
}
|
||||
|
||||
public async removeDb(ids: number[]) {
|
||||
await DependenceModel.destroy({ where: { id: ids } });
|
||||
await DependenceModel.nativeDelete({ id: ids });
|
||||
}
|
||||
|
||||
public async dependencies(
|
||||
{
|
||||
searchValue,
|
||||
@@ -129,6 +112,11 @@ export default class DependenceService {
|
||||
query: any = {},
|
||||
): Promise<Dependence[]> {
|
||||
let condition = query;
|
||||
const dependenceType =
|
||||
type && DependenceTypes[type] !== undefined
|
||||
? DependenceTypes[type]
|
||||
: undefined;
|
||||
await this.refreshInstalledStatuses(dependenceType);
|
||||
if (type && DependenceTypes[type] !== undefined) {
|
||||
condition.type = DependenceTypes[type];
|
||||
}
|
||||
@@ -136,13 +124,7 @@ export default class DependenceService {
|
||||
condition.status = status.split(',').map(Number);
|
||||
}
|
||||
if (searchValue) {
|
||||
const encodeText = encodeURI(searchValue);
|
||||
condition.name = {
|
||||
[Op.or]: [
|
||||
{ [Op.like]: `%${searchValue}%` },
|
||||
{ [Op.like]: `%${encodeText}%` },
|
||||
],
|
||||
};
|
||||
Object.assign(condition, textSearch(['name'], searchValue));
|
||||
}
|
||||
try {
|
||||
return await this.find(condition, sort);
|
||||
@@ -150,53 +132,6 @@ export default class DependenceService {
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
public startRefresh(type: RefreshType): {
|
||||
job: RefreshJob;
|
||||
accepted: boolean;
|
||||
} {
|
||||
if (this.activeRefreshJob) {
|
||||
return {
|
||||
job: this.activeRefreshJob,
|
||||
accepted: this.activeRefreshJob.type === type,
|
||||
};
|
||||
}
|
||||
|
||||
const job: RefreshJob = { id: randomUUID(), type, state: 'running' };
|
||||
this.activeRefreshJob = job;
|
||||
this.refreshJobs.set(job.id, job);
|
||||
while (this.refreshJobs.size > 20) {
|
||||
const oldestId = this.refreshJobs.keys().next().value;
|
||||
this.refreshJobs.delete(oldestId);
|
||||
}
|
||||
|
||||
void this.refreshInstalledStatuses(DependenceTypes[type])
|
||||
.then(() => {
|
||||
job.state = 'completed';
|
||||
})
|
||||
.catch((error) => {
|
||||
this.logger.error('Dependency refresh failed: %o', error);
|
||||
job.state = 'failed';
|
||||
})
|
||||
.finally(() => {
|
||||
if (this.activeRefreshJob === job) {
|
||||
this.activeRefreshJob = undefined;
|
||||
}
|
||||
});
|
||||
|
||||
return { job, accepted: true };
|
||||
}
|
||||
|
||||
public getRefreshJob(id: string): RefreshJob | undefined {
|
||||
return this.refreshJobs.get(id);
|
||||
}
|
||||
|
||||
public getActiveRefreshJob(): RefreshJob | undefined {
|
||||
return this.activeRefreshJob?.state === 'running'
|
||||
? this.activeRefreshJob
|
||||
: undefined;
|
||||
}
|
||||
|
||||
private async refreshInstalledStatuses(type?: DependenceTypes) {
|
||||
const cacheDependenceTypes = [
|
||||
DependenceTypes.nodejs,
|
||||
@@ -205,42 +140,35 @@ export default class DependenceService {
|
||||
if (type !== undefined && !cacheDependenceTypes.includes(type)) {
|
||||
return;
|
||||
}
|
||||
|
||||
const docs = await DependenceModel.findAll({
|
||||
where: {
|
||||
const docs = await DependenceModel.find(
|
||||
{
|
||||
status: DependenceStatus.installed,
|
||||
type: type === undefined ? { [Op.in]: cacheDependenceTypes } : type,
|
||||
type: type === undefined ? { ['$in']: cacheDependenceTypes } : type,
|
||||
},
|
||||
});
|
||||
const checkableDocs = docs.filter(
|
||||
{},
|
||||
);
|
||||
const checks = await concurrentRun(
|
||||
docs
|
||||
.filter(
|
||||
(doc) =>
|
||||
doc.type !== DependenceTypes.python3 ||
|
||||
!isPythonSourceDependency(doc.name),
|
||||
);
|
||||
const checks = await concurrentRun(
|
||||
checkableDocs.map((doc) => async () => this.isDependenceInstalled(doc)),
|
||||
)
|
||||
.map((doc) => async () => {
|
||||
return (await this.isDependenceInstalled(doc)) ? undefined : doc.id;
|
||||
}),
|
||||
5,
|
||||
);
|
||||
|
||||
for (const [index, installed] of (checks || []).entries()) {
|
||||
if (installed) continue;
|
||||
const doc = checkableDocs[index];
|
||||
await DependenceModel.update(
|
||||
const missingIds = (checks || []).filter(
|
||||
(id): id is number => id !== undefined,
|
||||
);
|
||||
if (missingIds.length) {
|
||||
await DependenceModel.nativeUpdate(
|
||||
{ id: missingIds },
|
||||
{ status: DependenceStatus.installFailed },
|
||||
{
|
||||
where: {
|
||||
id: doc.id,
|
||||
status: DependenceStatus.installed,
|
||||
name: doc.name,
|
||||
type: doc.type,
|
||||
updatedAt: (doc as typeof doc & { updatedAt: Date }).updatedAt,
|
||||
// Sequelize's automatic timestamp is absent from Dependence's attribute type.
|
||||
} as any,
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
private async isDependenceInstalled(dependency: Dependence) {
|
||||
let depName = dependency.name.trim();
|
||||
const depVersionStr = versionDependenceCommandTypes[dependency.type];
|
||||
@@ -258,7 +186,6 @@ export default class DependenceService {
|
||||
depVersion = parsedVersion;
|
||||
}
|
||||
}
|
||||
|
||||
const depInfo = (
|
||||
await promiseExecSuccess(getGetCommand(dependency.type, depName))
|
||||
)
|
||||
@@ -268,12 +195,10 @@ export default class DependenceService {
|
||||
(dependency.type === DependenceTypes.nodejs &&
|
||||
depInfo.split(' ')?.[0] === depName) ||
|
||||
dependency.type === DependenceTypes.python3;
|
||||
|
||||
return Boolean(
|
||||
depInfo && nameMatches && (!depVersion || depInfo.includes(depVersion)),
|
||||
);
|
||||
}
|
||||
|
||||
public installDependenceOneByOne(
|
||||
docs: Dependence[],
|
||||
isInstall: boolean = true,
|
||||
@@ -282,32 +207,27 @@ export default class DependenceService {
|
||||
docs.forEach((dep) => {
|
||||
this.installOrUninstallDependency(dep, isInstall, force);
|
||||
});
|
||||
|
||||
return taskLimit.waitDependencyQueueDone();
|
||||
}
|
||||
|
||||
public async reInstall(ids: number[]): Promise<Dependence[]> {
|
||||
await DependenceModel.update(
|
||||
await DependenceModel.nativeUpdate(
|
||||
{ id: ids },
|
||||
{ status: DependenceStatus.queued, log: [] },
|
||||
{ where: { id: ids } },
|
||||
);
|
||||
|
||||
const docs = await DependenceModel.findAll({ where: { id: ids } });
|
||||
const docs = await DependenceModel.find({ id: ids }, {});
|
||||
for (const doc of docs) {
|
||||
taskLimit.removeQueuedDependency(doc);
|
||||
}
|
||||
this.installDependenceOneByOne(docs, true, true);
|
||||
return docs;
|
||||
}
|
||||
|
||||
public async cancel(ids: number[]) {
|
||||
const docs = await DependenceModel.findAll({ where: { id: ids } });
|
||||
const docs = await DependenceModel.find({ id: ids }, {});
|
||||
for (const doc of docs) {
|
||||
taskLimit.removeQueuedDependency(doc);
|
||||
let depInstallCommand = getInstallCommand(doc.type, doc.name);
|
||||
let depUnInstallCommand = getUninstallCommand(doc.type, doc.name);
|
||||
const isLinuxDependence = doc.type === DependenceTypes.linux;
|
||||
|
||||
if (isLinuxDependence) {
|
||||
const osType = await detectOS();
|
||||
if (!osType) {
|
||||
@@ -325,44 +245,37 @@ export default class DependenceService {
|
||||
pid && (await killTask(pid));
|
||||
}
|
||||
}
|
||||
await DependenceModel.update(
|
||||
await DependenceModel.nativeUpdate(
|
||||
{ id: ids },
|
||||
{ status: DependenceStatus.cancelled },
|
||||
{ where: { id: ids } },
|
||||
);
|
||||
}
|
||||
|
||||
private async find(query: any, sort: any = []): Promise<Dependence[]> {
|
||||
const docs = await DependenceModel.findAll({
|
||||
where: { ...query },
|
||||
order: [...sort, ['createdAt', 'DESC']],
|
||||
});
|
||||
const docs = await DependenceModel.find(
|
||||
{ ...query },
|
||||
{
|
||||
orderBy: orderBy([...sort, ['createdAt', 'DESC']]),
|
||||
},
|
||||
);
|
||||
return docs;
|
||||
}
|
||||
|
||||
public async getDb(
|
||||
query: FindOptions<Dependence>['where'],
|
||||
): Promise<Dependence> {
|
||||
const doc: any = await DependenceModel.findOne({ where: { ...query } });
|
||||
public async getDb(query: QuerySpec['where']): Promise<Dependence> {
|
||||
const doc: any = await DependenceModel.findOne({ ...query }, {});
|
||||
if (!doc) {
|
||||
throw new Error(`Dependency ${JSON.stringify(query)} not found`);
|
||||
}
|
||||
return doc.get({ plain: true });
|
||||
return doc;
|
||||
}
|
||||
|
||||
private async updateLog(ids: number[], log: string): Promise<void> {
|
||||
taskLimit.updateDepLog(async () => {
|
||||
const docs = await DependenceModel.findAll({ where: { id: ids } });
|
||||
const docs = await DependenceModel.find({ id: ids }, {});
|
||||
for (const doc of docs) {
|
||||
const newLog = doc?.log ? [...doc.log, log] : [log];
|
||||
await DependenceModel.update(
|
||||
{ log: newLog },
|
||||
{ where: { id: doc.id } },
|
||||
);
|
||||
await DependenceModel.nativeUpdate({ id: doc.id }, { log: newLog });
|
||||
}
|
||||
return null;
|
||||
});
|
||||
}
|
||||
|
||||
public installOrUninstallDependency(
|
||||
dependency: Dependence,
|
||||
isInstall: boolean = true,
|
||||
@@ -379,14 +292,14 @@ export default class DependenceService {
|
||||
if (!isInstall && force) {
|
||||
return this.removeDb([dependency.id!]).then(() => null);
|
||||
}
|
||||
return DependenceModel.update(
|
||||
return DependenceModel.nativeUpdate(
|
||||
{ id: dependency.id },
|
||||
{
|
||||
status: isInstall
|
||||
? DependenceStatus.installFailed
|
||||
: DependenceStatus.removeFailed,
|
||||
log: [String(error)],
|
||||
},
|
||||
{ where: { id: dependency.id } },
|
||||
).then(() => null);
|
||||
}
|
||||
return new Promise(async (resolve) => {
|
||||
@@ -407,9 +320,9 @@ export default class DependenceService {
|
||||
taskLimit.removeQueuedDependency(dependency);
|
||||
if (isLinuxDependence) {
|
||||
if (!osType) {
|
||||
await DependenceModel.update(
|
||||
await DependenceModel.nativeUpdate(
|
||||
{ id: depIds },
|
||||
{ status: DependenceStatus.installFailed },
|
||||
{ where: { id: depIds } },
|
||||
);
|
||||
const startTime = dayjs();
|
||||
const message = tf(
|
||||
@@ -432,12 +345,10 @@ export default class DependenceService {
|
||||
}
|
||||
linuxCommand = LINUX_DEPENDENCE_COMMAND[osType];
|
||||
}
|
||||
|
||||
const status = isInstall
|
||||
? DependenceStatus.installing
|
||||
: DependenceStatus.removing;
|
||||
await DependenceModel.update({ status }, { where: { id: depIds } });
|
||||
|
||||
await DependenceModel.nativeUpdate({ id: depIds }, { status });
|
||||
let command = validatedCommand;
|
||||
if (isLinuxDependence) {
|
||||
command = isInstall
|
||||
@@ -445,7 +356,6 @@ export default class DependenceService {
|
||||
: `${linuxCommand.uninstall} ${depName.trim()}`;
|
||||
}
|
||||
const startTime = dayjs();
|
||||
|
||||
const message = tf(
|
||||
'开始%s依赖 %s,开始时间 %s\n\n',
|
||||
actionText,
|
||||
@@ -459,7 +369,6 @@ export default class DependenceService {
|
||||
status,
|
||||
});
|
||||
this.updateLog(depIds, message);
|
||||
|
||||
// 判断是否已经安装过依赖
|
||||
// pip must resolve optional dependencies even if the base distribution
|
||||
// is already present; its version alone cannot prove extras are ready.
|
||||
@@ -473,7 +382,6 @@ export default class DependenceService {
|
||||
if (isLinuxDependence) {
|
||||
getCommand = `${linuxCommand.info} ${depName}`;
|
||||
}
|
||||
|
||||
let depVersion = '';
|
||||
if (!isPythonDependence && depName.includes(depVersionStr)) {
|
||||
const symbolRegx = new RegExp(
|
||||
@@ -488,7 +396,6 @@ export default class DependenceService {
|
||||
const depInfo = (await promiseExecSuccess(getCommand))
|
||||
.replace(/\s{2,}/, ' ')
|
||||
.replace(/\s+$/, '');
|
||||
|
||||
if (
|
||||
depInfo &&
|
||||
((isNodeDependence && depInfo.split(' ')?.[0] === depName) ||
|
||||
@@ -513,9 +420,9 @@ export default class DependenceService {
|
||||
status: DependenceStatus.installed,
|
||||
});
|
||||
this.updateLog(depIds, _message);
|
||||
await DependenceModel.update(
|
||||
await DependenceModel.nativeUpdate(
|
||||
{ id: depIds },
|
||||
{ status: DependenceStatus.installed },
|
||||
{ where: { id: depIds } },
|
||||
);
|
||||
return resolve(null);
|
||||
}
|
||||
@@ -529,7 +436,6 @@ export default class DependenceService {
|
||||
const cp = spawn(`${proxyStr} ${command}`, {
|
||||
shell: '/bin/bash',
|
||||
});
|
||||
|
||||
cp.stdout.on('data', async (data) => {
|
||||
this.sockService.sendMessage({
|
||||
type: socketMessageType,
|
||||
@@ -539,7 +445,6 @@ export default class DependenceService {
|
||||
});
|
||||
this.updateLog(depIds, data.toString());
|
||||
});
|
||||
|
||||
cp.stderr.on('data', async (data) => {
|
||||
this.sockService.sendMessage({
|
||||
type: socketMessageType,
|
||||
@@ -549,7 +454,6 @@ export default class DependenceService {
|
||||
});
|
||||
this.updateLog(depIds, data.toString());
|
||||
});
|
||||
|
||||
cp.on('error', async (err) => {
|
||||
this.sockService.sendMessage({
|
||||
type: socketMessageType,
|
||||
@@ -559,12 +463,10 @@ export default class DependenceService {
|
||||
});
|
||||
this.updateLog(depIds, JSON.stringify(err));
|
||||
});
|
||||
|
||||
cp.on('exit', async (code) => {
|
||||
const endTime = dayjs();
|
||||
const isSucceed = code === 0;
|
||||
const resultText = isSucceed ? t('成功') : t('失败');
|
||||
|
||||
const message =
|
||||
'\n' +
|
||||
tf(
|
||||
@@ -588,24 +490,20 @@ export default class DependenceService {
|
||||
status: exitStatus,
|
||||
});
|
||||
this.updateLog(depIds, message);
|
||||
|
||||
const docs = await DependenceModel.findAll({ where: { id: depIds } });
|
||||
const docs = await DependenceModel.find({ id: depIds }, {});
|
||||
const _docIds = docs
|
||||
.filter((x) => x.status !== DependenceStatus.cancelled)
|
||||
.map((x) => x.id!);
|
||||
|
||||
if (_docIds.length > 0) {
|
||||
await DependenceModel.update(
|
||||
await DependenceModel.nativeUpdate(
|
||||
{ id: _docIds },
|
||||
{ status: exitStatus },
|
||||
{ where: { id: _docIds } },
|
||||
);
|
||||
}
|
||||
|
||||
// 如果删除依赖成功或者强制删除
|
||||
if ((isSucceed || force) && !isInstall) {
|
||||
this.removeDb(depIds);
|
||||
}
|
||||
|
||||
resolve(null);
|
||||
});
|
||||
});
|
||||
|
||||
+44
-107
@@ -1,5 +1,6 @@
|
||||
import { textSearch } from '../data/queries';
|
||||
import { Query, QuerySpec, orderBy } from '../data/queries';
|
||||
import groupBy from 'lodash/groupBy';
|
||||
import { FindOptions, Op } from 'sequelize';
|
||||
import { Inject, Service } from 'typedi';
|
||||
import winston from 'winston';
|
||||
import config from '../config';
|
||||
@@ -13,18 +14,14 @@ import {
|
||||
stepPosition,
|
||||
} from '../data/env';
|
||||
import { writeFileWithLock } from '../shared/utils';
|
||||
import { sequelize } from '../data';
|
||||
import {
|
||||
assertAllowedTaskEnvName,
|
||||
isAllowedTaskEnvName,
|
||||
} from '../shared/taskEnvName';
|
||||
|
||||
import { database } from '../data';
|
||||
@Service()
|
||||
export default class EnvService {
|
||||
constructor(@Inject('logger') private logger: winston.Logger) { }
|
||||
|
||||
constructor(
|
||||
@Inject('logger')
|
||||
private logger: winston.Logger,
|
||||
) {}
|
||||
public async create(payloads: Env[]): Promise<Env[]> {
|
||||
payloads.forEach((payload) => assertAllowedTaskEnvName(payload.name));
|
||||
const envs = await this.envs();
|
||||
let position = initPosition;
|
||||
if (
|
||||
@@ -44,35 +41,29 @@ export default class EnvService {
|
||||
await this.checkPosition(tabs[tabs.length - 1].position!);
|
||||
return docs;
|
||||
}
|
||||
|
||||
public async insert(payloads: Env[]): Promise<Env[]> {
|
||||
const result: Env[] = [];
|
||||
for (const env of payloads) {
|
||||
const doc = await EnvModel.create(env, { returning: true });
|
||||
const doc = await EnvModel.insert(env);
|
||||
result.push(doc);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
public async update(payload: Env): Promise<Env> {
|
||||
const doc = await this.getDb({ id: payload.id });
|
||||
const tab = new Env({ ...doc, ...payload });
|
||||
assertAllowedTaskEnvName(tab.name);
|
||||
const newDoc = await this.updateDb(tab);
|
||||
await this.set_envs();
|
||||
return newDoc;
|
||||
}
|
||||
|
||||
private async updateDb(payload: Env): Promise<Env> {
|
||||
await EnvModel.update({ ...payload }, { where: { id: payload.id } });
|
||||
await EnvModel.nativeUpdate({ id: payload.id }, { ...payload });
|
||||
return await this.getDb({ id: payload.id });
|
||||
}
|
||||
|
||||
public async remove(ids: number[]) {
|
||||
await EnvModel.destroy({ where: { id: ids } });
|
||||
await EnvModel.nativeDelete({ id: ids });
|
||||
await this.set_envs();
|
||||
}
|
||||
|
||||
public async move(
|
||||
id: number,
|
||||
{
|
||||
@@ -95,16 +86,13 @@ export default class EnvService {
|
||||
? (envs[toIndex].position! + envs[toIndex - 1].position!) / 2
|
||||
: (envs[toIndex].position! + envs[toIndex + 1].position!) / 2;
|
||||
}
|
||||
|
||||
const newDoc = await this.update({
|
||||
id,
|
||||
position: this.getPrecisionPosition(targetPosition),
|
||||
});
|
||||
|
||||
await this.checkPosition(targetPosition, envs[toIndex].position!);
|
||||
return newDoc;
|
||||
}
|
||||
|
||||
private async checkPosition(position: number, edge: number = 0) {
|
||||
const precisionPosition = this.getPrecisionPosition(position);
|
||||
if (
|
||||
@@ -120,147 +108,97 @@ export default class EnvService {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private getPrecisionPosition(position: number): number {
|
||||
return Math.trunc(parseFloat(position.toPrecision(16)));
|
||||
}
|
||||
|
||||
public async envs(searchText: string = '', query: any = {}): Promise<Env[]> {
|
||||
let condition = { ...query };
|
||||
if (searchText) {
|
||||
const encodeText = encodeURI(searchText);
|
||||
const reg = {
|
||||
[Op.or]: [
|
||||
{ [Op.like]: `%${searchText}%` },
|
||||
{ [Op.like]: `%${encodeText}%` },
|
||||
],
|
||||
};
|
||||
|
||||
condition = {
|
||||
...condition,
|
||||
[Op.or]: [
|
||||
{
|
||||
name: reg,
|
||||
},
|
||||
{
|
||||
value: reg,
|
||||
},
|
||||
{
|
||||
remarks: reg,
|
||||
},
|
||||
],
|
||||
...textSearch(['name', 'value', 'remarks'], searchText),
|
||||
};
|
||||
}
|
||||
try {
|
||||
const result = await this.find(condition, [
|
||||
[sequelize.literal('COALESCE(`isPinned`, 0)'), 'DESC'],
|
||||
['isPinned', 'DESC'],
|
||||
['position', 'DESC'],
|
||||
['createdAt', 'ASC'],
|
||||
]);
|
||||
return result.map((env) => ({
|
||||
...env,
|
||||
securityBlocked: !isAllowedTaskEnvName(env.name),
|
||||
}));
|
||||
return result;
|
||||
} catch (error) {
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
private async find(query: any, sort: any = []): Promise<Env[]> {
|
||||
const docs = await EnvModel.findAll({
|
||||
where: { ...query },
|
||||
order: [...sort],
|
||||
});
|
||||
return docs.map((x) => x.get({ plain: true }));
|
||||
const docs = await EnvModel.find(
|
||||
{ ...query },
|
||||
{
|
||||
orderBy: orderBy([...sort]),
|
||||
},
|
||||
);
|
||||
return docs.map((x) => x);
|
||||
}
|
||||
|
||||
public async getDb(query: FindOptions<Env>['where']): Promise<Env> {
|
||||
const doc: any = await EnvModel.findOne({ where: { ...query } });
|
||||
public async getDb(query: QuerySpec['where']): Promise<Env> {
|
||||
const doc: any = await EnvModel.findOne({ ...query }, {});
|
||||
if (!doc) {
|
||||
throw new Error(`Env ${JSON.stringify(query)} not found`);
|
||||
}
|
||||
return doc.get({ plain: true });
|
||||
return doc;
|
||||
}
|
||||
|
||||
public async disabled(ids: number[]) {
|
||||
await EnvModel.update(
|
||||
{ status: EnvStatus.disabled },
|
||||
{ where: { id: ids } },
|
||||
);
|
||||
await EnvModel.nativeUpdate({ id: ids }, { status: EnvStatus.disabled });
|
||||
await this.set_envs();
|
||||
}
|
||||
|
||||
public async enabled(ids: number[]) {
|
||||
const docs = await EnvModel.findAll({ where: { id: ids } });
|
||||
docs.forEach((doc) => assertAllowedTaskEnvName(doc.name));
|
||||
await EnvModel.update({ status: EnvStatus.normal }, { where: { id: ids } });
|
||||
await EnvModel.nativeUpdate({ id: ids }, { status: EnvStatus.normal });
|
||||
await this.set_envs();
|
||||
}
|
||||
|
||||
public async updateNames({ ids, name }: { ids: number[]; name: string }) {
|
||||
assertAllowedTaskEnvName(name);
|
||||
await EnvModel.update({ name }, { where: { id: ids } });
|
||||
await EnvModel.nativeUpdate({ id: ids }, { name });
|
||||
await this.set_envs();
|
||||
}
|
||||
|
||||
public async pin(ids: number[]) {
|
||||
await EnvModel.update({ isPinned: 1 }, { where: { id: ids } });
|
||||
await EnvModel.nativeUpdate({ id: ids }, { isPinned: 1 });
|
||||
}
|
||||
|
||||
public async unPin(ids: number[]) {
|
||||
await EnvModel.update({ isPinned: 0 }, { where: { id: ids } });
|
||||
await EnvModel.nativeUpdate({ id: ids }, { isPinned: 0 });
|
||||
}
|
||||
|
||||
public async addLabels(ids: number[], labels: string[]) {
|
||||
await sequelize.transaction(async (transaction) => {
|
||||
const docs = await EnvModel.findAll({
|
||||
where: { id: ids },
|
||||
transaction,
|
||||
});
|
||||
await database.transaction(async () => {
|
||||
const docs = await EnvModel.find({ id: ids }, {});
|
||||
for (const doc of docs) {
|
||||
const env = doc.get({ plain: true });
|
||||
await EnvModel.update(
|
||||
const env = doc;
|
||||
await EnvModel.nativeUpdate(
|
||||
{ id: env.id },
|
||||
{ labels: Array.from(new Set([...(env.labels || []), ...labels])) },
|
||||
{ where: { id: env.id }, transaction },
|
||||
);
|
||||
}
|
||||
});
|
||||
return await this.find({ id: ids });
|
||||
}
|
||||
|
||||
public async removeLabels(ids: number[], labels: string[]) {
|
||||
await sequelize.transaction(async (transaction) => {
|
||||
const docs = await EnvModel.findAll({
|
||||
where: { id: ids },
|
||||
transaction,
|
||||
});
|
||||
await database.transaction(async () => {
|
||||
const docs = await EnvModel.find({ id: ids }, {});
|
||||
for (const doc of docs) {
|
||||
const env = doc.get({ plain: true });
|
||||
await EnvModel.update(
|
||||
const env = doc;
|
||||
await EnvModel.nativeUpdate(
|
||||
{ id: env.id },
|
||||
{
|
||||
labels: (env.labels || []).filter(
|
||||
(label: string) => !labels.includes(label),
|
||||
),
|
||||
},
|
||||
{ where: { id: env.id }, transaction },
|
||||
);
|
||||
}
|
||||
});
|
||||
return await this.find({ id: ids });
|
||||
}
|
||||
|
||||
public async set_envs() {
|
||||
const envs = await this.envs('', {
|
||||
name: { [Op.not]: null },
|
||||
name: { ['$ne']: null },
|
||||
status: EnvStatus.normal,
|
||||
});
|
||||
const invalid = envs.filter((env) => !isAllowedTaskEnvName(env.name));
|
||||
if (invalid.length > 0) {
|
||||
this.logger.warn(
|
||||
'Skipped reserved environment variables in task files: %s',
|
||||
JSON.stringify(invalid.map((env) => ({ id: env.id, name: env.name }))),
|
||||
);
|
||||
}
|
||||
const groups = groupBy(envs, 'name');
|
||||
let env_string = '';
|
||||
let js_env_string = '';
|
||||
@@ -268,9 +206,8 @@ export default class EnvService {
|
||||
for (const key in groups) {
|
||||
if (Object.prototype.hasOwnProperty.call(groups, key)) {
|
||||
const group = groups[key];
|
||||
|
||||
// Ignore invalid and reserved names, including legacy database rows.
|
||||
if (isAllowedTaskEnvName(key)) {
|
||||
// 忽略不符合bash要求的环境变量名称
|
||||
if (/^[a-zA-Z_][0-9a-zA-Z_]*$/.test(key)) {
|
||||
let value = group
|
||||
.map((x) => x.value)
|
||||
.join('&')
|
||||
@@ -281,9 +218,9 @@ export default class EnvService {
|
||||
.map((x) => x.value)
|
||||
.join('&')
|
||||
.replace(/\\/g, '\\\\')}`;
|
||||
js_env_string += `process.env[${JSON.stringify(key)}]=${JSON.stringify(
|
||||
group.map((x) => x.value).join('&'),
|
||||
)};\n`;
|
||||
js_env_string += `process.env[${JSON.stringify(
|
||||
key,
|
||||
)}]=${JSON.stringify(group.map((x) => x.value).join('&'))};\n`;
|
||||
py_env_string += `os.environ['${key}']='''${_env_value.replace(
|
||||
/\'/g,
|
||||
"\\'",
|
||||
|
||||
@@ -2,7 +2,8 @@ import { Server, ServerCredentials } from '@grpc/grpc-js';
|
||||
import { CronService } from '../protos/cron';
|
||||
import { HealthService } from '../protos/health';
|
||||
import { ApiService } from '../protos/api';
|
||||
import { registeredAdd, registeredDelete } from '../schedule/registeredPlans';
|
||||
import { addCron } from '../schedule/addCron';
|
||||
import { delCron } from '../schedule/delCron';
|
||||
import { setConcurrency } from '../schedule/setConcurrency';
|
||||
import { check } from '../schedule/health';
|
||||
import * as Api from '../schedule/api';
|
||||
@@ -27,7 +28,7 @@ export class GrpcServerService {
|
||||
async initialize() {
|
||||
try {
|
||||
this.server.addService(HealthService, { check });
|
||||
this.server.addService(CronService, { addCron: registeredAdd, delCron: registeredDelete, setConcurrency });
|
||||
this.server.addService(CronService, { addCron, delCron, setConcurrency });
|
||||
this.server.addService(ApiService, Api);
|
||||
|
||||
const tlsConfig = await initGrpcCerts();
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { database } from '../data';
|
||||
import { Service } from 'typedi';
|
||||
import Logger from '../loaders/logger';
|
||||
import cronClient from '../schedule/client';
|
||||
@@ -10,6 +11,7 @@ interface HealthStatus {
|
||||
services: {
|
||||
http: boolean;
|
||||
grpc: boolean;
|
||||
database: boolean;
|
||||
};
|
||||
metrics: {
|
||||
uptime: number;
|
||||
@@ -33,6 +35,7 @@ export class HealthService {
|
||||
services: {
|
||||
http: true,
|
||||
grpc: true,
|
||||
database: database.healthy,
|
||||
},
|
||||
metrics: {
|
||||
uptime: Math.floor((Date.now() - this.startTime) / 1000),
|
||||
@@ -66,6 +69,7 @@ export class HealthService {
|
||||
Logger.error('gRPC server check failed:', err);
|
||||
}
|
||||
|
||||
if (!status.services.database) status.status = 'error';
|
||||
return status;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,6 +8,6 @@ export default class LogService {
|
||||
constructor(@Inject('logger') private logger: winston.Logger) {}
|
||||
|
||||
public checkFilePath(filePath: string, fileName: string) {
|
||||
return resolveFileAccess(config.logPath, [filePath || '', fileName], ['.tmp']);
|
||||
return resolveFileAccess(config.logPath, [filePath || '', fileName]);
|
||||
}
|
||||
}
|
||||
|
||||
+21
-59
@@ -1,9 +1,9 @@
|
||||
import { textSearch } from '../data/queries';
|
||||
import { Service, Inject } from 'typedi';
|
||||
import winston from 'winston';
|
||||
import { createRandomString } from '../config/util';
|
||||
import { App, AppModel } from '../data/open';
|
||||
import { v4 as uuidV4 } from 'uuid';
|
||||
import sequelize, { Op } from 'sequelize';
|
||||
import { shareStore } from '../shared/store';
|
||||
import { t } from '../shared/i18n';
|
||||
import { lock } from 'proper-lockfile';
|
||||
@@ -11,18 +11,19 @@ import path from 'path';
|
||||
import os from 'os';
|
||||
import { writeFile, rename, rm, stat, chmod } from 'fs/promises';
|
||||
import config from '../config';
|
||||
|
||||
@Service()
|
||||
export default class OpenService {
|
||||
constructor(@Inject('logger') private logger: winston.Logger) {}
|
||||
|
||||
constructor(
|
||||
@Inject('logger')
|
||||
private logger: winston.Logger,
|
||||
) {}
|
||||
// Every database mutation and full authentication-cache publication shares
|
||||
// this cross-process lock. Lock a separate marker, not token.json itself.
|
||||
private async withAppsLock<T>(operation: () => Promise<T>): Promise<T> {
|
||||
const target = path.join(config.configPath, '.apps-state');
|
||||
const release = await lock(target, {
|
||||
realpath: false,
|
||||
stale: 10_000,
|
||||
stale: 10000,
|
||||
retries: { retries: 10, factor: 2, minTimeout: 100, maxTimeout: 3000 },
|
||||
});
|
||||
try {
|
||||
@@ -31,11 +32,10 @@ export default class OpenService {
|
||||
await release();
|
||||
}
|
||||
}
|
||||
|
||||
public async initializeSystemApp(): Promise<void> {
|
||||
await this.withAppsLock(async () => {
|
||||
const doc = await AppModel.findOne({ where: { name: 'system' } });
|
||||
const app = doc?.get({ plain: true });
|
||||
const doc = await AppModel.findOne({ name: 'system' }, {});
|
||||
const app = doc;
|
||||
if (!app) {
|
||||
await this.insert({
|
||||
name: 'system',
|
||||
@@ -44,26 +44,23 @@ export default class OpenService {
|
||||
client_secret: createRandomString(24, 24),
|
||||
});
|
||||
} else if (!app.scopes.includes('dashboard')) {
|
||||
await AppModel.update(
|
||||
await AppModel.nativeUpdate(
|
||||
{ id: app.id },
|
||||
{ scopes: [...app.scopes, 'dashboard'] },
|
||||
{ where: { id: app.id } },
|
||||
);
|
||||
}
|
||||
await shareStore.updateApps(await this.find({}));
|
||||
});
|
||||
}
|
||||
|
||||
public async refreshApps(): Promise<void> {
|
||||
await this.withAppsLock(async () => {
|
||||
await shareStore.updateApps(await this.find({}));
|
||||
});
|
||||
}
|
||||
|
||||
public async findApps(): Promise<App[] | null> {
|
||||
const docs = await this.find({});
|
||||
return docs;
|
||||
}
|
||||
|
||||
public async create(payload: App): Promise<App> {
|
||||
return this.withAppsLock(async () => {
|
||||
const tab = { ...payload };
|
||||
@@ -75,12 +72,10 @@ export default class OpenService {
|
||||
return { ...doc, tokens: [] };
|
||||
});
|
||||
}
|
||||
|
||||
private async insert(payload: App): Promise<App> {
|
||||
const doc = await AppModel.create(payload, { returning: true });
|
||||
return doc.get({ plain: true });
|
||||
const doc = await AppModel.insert(payload);
|
||||
return doc;
|
||||
}
|
||||
|
||||
public async update(payload: App): Promise<App> {
|
||||
const newDoc = await this.updateDb({
|
||||
name: payload.name,
|
||||
@@ -89,42 +84,28 @@ export default class OpenService {
|
||||
} as App);
|
||||
return { ...newDoc, tokens: [] };
|
||||
}
|
||||
|
||||
private async updateDb(payload: Partial<App>): Promise<App> {
|
||||
return this.withAppsLock(async () => {
|
||||
const target = await AppModel.findOne({ where: { id: payload.id } });
|
||||
if (target?.name === 'system' || payload.name === 'system') {
|
||||
throw Object.assign(new Error(t('暂无权限')), { status: 403 });
|
||||
}
|
||||
await AppModel.update(payload, { where: { id: payload.id } });
|
||||
await AppModel.nativeUpdate({ id: payload.id }, payload);
|
||||
const apps = await this.find({});
|
||||
await shareStore.updateApps(apps);
|
||||
return apps?.find((x) => x.id === payload.id) as App;
|
||||
});
|
||||
}
|
||||
|
||||
public async getDb(query: Record<string, any>): Promise<App> {
|
||||
const doc = await AppModel.findOne({ where: query });
|
||||
const doc = await AppModel.findOne(query, {});
|
||||
if (!doc) {
|
||||
throw new Error(`App ${JSON.stringify(query)} not found`);
|
||||
}
|
||||
return doc.get({ plain: true });
|
||||
return doc;
|
||||
}
|
||||
|
||||
public async remove(ids: number[]) {
|
||||
return this.withAppsLock(async () => {
|
||||
const systemApp = await AppModel.findOne({
|
||||
where: { id: ids, name: 'system' },
|
||||
});
|
||||
if (systemApp) {
|
||||
throw Object.assign(new Error(t('暂无权限')), { status: 403 });
|
||||
}
|
||||
await AppModel.destroy({ where: { id: ids } });
|
||||
await AppModel.nativeDelete({ id: ids });
|
||||
const apps = await this.find({});
|
||||
await shareStore.updateApps(apps);
|
||||
});
|
||||
}
|
||||
|
||||
public async resetSecret(id: number): Promise<App> {
|
||||
const tab: Partial<App> = {
|
||||
client_secret: createRandomString(24, 24),
|
||||
@@ -140,7 +121,6 @@ export default class OpenService {
|
||||
const newDoc = await this.updateDb(tab);
|
||||
return newDoc;
|
||||
}
|
||||
|
||||
public async list(
|
||||
searchText: string = '',
|
||||
sort: any = {},
|
||||
@@ -148,18 +128,7 @@ export default class OpenService {
|
||||
): Promise<App[]> {
|
||||
let condition = { ...query };
|
||||
if (searchText) {
|
||||
const encodeText = encodeURI(searchText);
|
||||
const reg = {
|
||||
[Op.or]: [
|
||||
{ [Op.like]: `%${searchText}%` },
|
||||
{ [Op.like]: `%${encodeText}%` },
|
||||
],
|
||||
};
|
||||
|
||||
condition = {
|
||||
...condition,
|
||||
name: reg,
|
||||
};
|
||||
condition = { ...condition, ...textSearch(['name'], searchText) };
|
||||
}
|
||||
try {
|
||||
const result = await this.find(condition);
|
||||
@@ -170,19 +139,16 @@ export default class OpenService {
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
private async find(query: Record<string, any>, sort?: any): Promise<App[]> {
|
||||
const docs = await AppModel.findAll({ where: { ...query } });
|
||||
return docs.map((x) => x.get({ plain: true }));
|
||||
const docs = await AppModel.find({ ...query }, {});
|
||||
return docs.map((x) => x);
|
||||
}
|
||||
|
||||
public async authToken(credentials: {
|
||||
client_id: string;
|
||||
client_secret: string;
|
||||
}): Promise<any> {
|
||||
return this.withAppsLock(() => this.issueToken(credentials));
|
||||
}
|
||||
|
||||
// Caller holds withAppsLock through database update and cache publication.
|
||||
private async issueToken({
|
||||
client_id,
|
||||
@@ -193,7 +159,7 @@ export default class OpenService {
|
||||
}): Promise<any> {
|
||||
let token = uuidV4();
|
||||
const expiration = Math.round(Date.now() / 1000) + 2592000; // 2592000 30天
|
||||
const doc = await AppModel.findOne({ where: { client_id, client_secret } });
|
||||
const doc = await AppModel.findOne({ client_id, client_secret }, {});
|
||||
if (doc) {
|
||||
const timestamp = Math.round(Date.now() / 1000);
|
||||
const invalidTokens = (doc.tokens || []).filter(
|
||||
@@ -209,10 +175,7 @@ export default class OpenService {
|
||||
} else {
|
||||
tokens = [...invalidTokens, { value: token, expiration }];
|
||||
}
|
||||
await AppModel.update(
|
||||
{ tokens },
|
||||
{ where: { client_id, client_secret } },
|
||||
);
|
||||
await AppModel.nativeUpdate({ client_id, client_secret }, { tokens });
|
||||
const apps = await this.find({});
|
||||
await shareStore.updateApps(apps);
|
||||
return {
|
||||
@@ -227,7 +190,6 @@ export default class OpenService {
|
||||
return { code: 400, message: t('client_id 或 client_seret 有误') };
|
||||
}
|
||||
}
|
||||
|
||||
public async generateSystemToken(renew = false): Promise<{
|
||||
value: string;
|
||||
expiration: number;
|
||||
|
||||
+36
-83
@@ -1,13 +1,10 @@
|
||||
import fs from 'fs/promises';
|
||||
import path from 'path';
|
||||
import dayjs from 'dayjs';
|
||||
import { literal, Op } from 'sequelize';
|
||||
import { Service } from 'typedi';
|
||||
import config from '../config';
|
||||
import { CrontabStatModel } from '../data/cronStats';
|
||||
import { sequelize } from '../data';
|
||||
import { TriggerHistory } from '../shared/triggerHistory';
|
||||
import { prunedExitMigrationId } from '../shared/schemaMigrations';
|
||||
import { database } from '../data';
|
||||
import { InstanceStatus, RunningInstanceModel } from '../data/runningInstance';
|
||||
import { AuthDataType, SystemModel } from '../data/system';
|
||||
import {
|
||||
@@ -17,73 +14,63 @@ import {
|
||||
normalizeRetentionPolicy,
|
||||
RetentionPolicy,
|
||||
} from '../shared/retention';
|
||||
|
||||
export interface StorageCleanupRequest extends RetentionPolicy {
|
||||
dependenceCacheTypes?: DependenceCacheType[];
|
||||
compactDatabase?: boolean;
|
||||
}
|
||||
|
||||
function runningInstanceWhere(cutoffMs: number) {
|
||||
const cutoff = cutoffMs / 1000;
|
||||
function runningInstanceWhere(days: number) {
|
||||
const cutoff = dayjs().subtract(days, 'day').unix();
|
||||
return {
|
||||
status: { [Op.ne]: InstanceStatus.running },
|
||||
id: { [Op.notIn]: literal(`(SELECT instance_id FROM CronTriggers WHERE instance_id IS NOT NULL
|
||||
AND (exit_pending=1 OR state IN ('queued','running') OR finished_at IS NULL OR observed_at >= ${cutoffMs} OR finished_at >= ${cutoffMs}))`) },
|
||||
[Op.or]: [
|
||||
{ finished_at: { [Op.lt]: cutoff } },
|
||||
status: { ['$ne']: InstanceStatus.running },
|
||||
['$or']: [
|
||||
{ finished_at: { ['$lt']: cutoff } },
|
||||
{
|
||||
finished_at: { [Op.is]: null },
|
||||
started_at: { [Op.lt]: cutoff },
|
||||
finished_at: { ['$eq']: null },
|
||||
started_at: { ['$lt']: cutoff },
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
function retentionCutoffs(policy: RetentionPolicy) {
|
||||
const now = dayjs();
|
||||
function cronStatWhere(days: number) {
|
||||
return {
|
||||
history: now.subtract(policy.runningInstanceRetentionDays, 'day').startOf('second').valueOf(),
|
||||
firstDay: now.subtract(policy.cronStatRetentionDays, 'day').format('YYYY-MM-DD'),
|
||||
date: { ['$lt']: dayjs().subtract(days, 'day').format('YYYY-MM-DD') },
|
||||
};
|
||||
}
|
||||
|
||||
@Service()
|
||||
export default class RetentionService {
|
||||
public async updatePolicy(policy: Partial<RetentionPolicy>) {
|
||||
const normalized = normalizeRetentionPolicy(policy);
|
||||
const systemConfig = await SystemModel.findOne({
|
||||
where: { type: AuthDataType.systemConfig },
|
||||
});
|
||||
const systemConfig = await SystemModel.findOne(
|
||||
{ type: AuthDataType.systemConfig },
|
||||
{},
|
||||
);
|
||||
if (!systemConfig) {
|
||||
throw new Error('System config not found');
|
||||
}
|
||||
await SystemModel.update(
|
||||
await SystemModel.nativeUpdate(
|
||||
{ id: systemConfig.id },
|
||||
{
|
||||
info: {
|
||||
...systemConfig.info,
|
||||
...normalized,
|
||||
},
|
||||
},
|
||||
{ where: { id: systemConfig.id } },
|
||||
);
|
||||
return normalized;
|
||||
}
|
||||
|
||||
public async preview(request: StorageCleanupRequest, cutoffs = retentionCutoffs(normalizeRetentionPolicy(request))) {
|
||||
public async preview(request: StorageCleanupRequest) {
|
||||
const policy = normalizeRetentionPolicy(request);
|
||||
const dependenceCacheTypes = (request.dependenceCacheTypes || []).filter(
|
||||
isDependenceCacheType,
|
||||
);
|
||||
const [runningInstances, cronStats, dependenceCaches, triggers] = await Promise.all([
|
||||
const [runningInstances, cronStats, dependenceCaches] = await Promise.all([
|
||||
policy.runningInstanceRetentionDays > 0
|
||||
? RunningInstanceModel.count({
|
||||
where: runningInstanceWhere(cutoffs.history),
|
||||
})
|
||||
? RunningInstanceModel.count(
|
||||
runningInstanceWhere(policy.runningInstanceRetentionDays),
|
||||
)
|
||||
: 0,
|
||||
policy.cronStatRetentionDays > 0
|
||||
? CrontabStatModel.count({
|
||||
where: { date: { [Op.lt]: cutoffs.firstDay } },
|
||||
})
|
||||
? CrontabStatModel.count(cronStatWhere(policy.cronStatRetentionDays))
|
||||
: 0,
|
||||
Promise.all(
|
||||
dependenceCacheTypes.map(async (type) => ({
|
||||
@@ -93,15 +80,10 @@ export default class RetentionService {
|
||||
),
|
||||
})),
|
||||
),
|
||||
policy.runningInstanceRetentionDays > 0
|
||||
? new TriggerHistory(sequelize).countExpired(cutoffs.history)
|
||||
: 0,
|
||||
]);
|
||||
|
||||
return {
|
||||
policy,
|
||||
runningInstances,
|
||||
triggers,
|
||||
cronStats,
|
||||
dependenceCaches,
|
||||
dependenceCacheBytes: dependenceCaches.reduce(
|
||||
@@ -111,50 +93,23 @@ export default class RetentionService {
|
||||
compactDatabase: Boolean(request.compactDatabase),
|
||||
};
|
||||
}
|
||||
|
||||
public async cleanup(request: StorageCleanupRequest) {
|
||||
const cutoffs = retentionCutoffs(normalizeRetentionPolicy(request));
|
||||
const preview = await this.preview(request, cutoffs);
|
||||
const deleted = await sequelize.transaction(async (transaction) => {
|
||||
const history = new TriggerHistory(sequelize);
|
||||
if (preview.policy.runningInstanceRetentionDays || preview.policy.cronStatRetentionDays) {
|
||||
await history.replayPublishedExits(transaction);
|
||||
}
|
||||
const preview = await this.preview(request);
|
||||
const deleted = await database.transaction(async () => {
|
||||
const runningInstances =
|
||||
preview.policy.runningInstanceRetentionDays > 0
|
||||
? await RunningInstanceModel.destroy({
|
||||
where: runningInstanceWhere(cutoffs.history),
|
||||
transaction,
|
||||
})
|
||||
? await RunningInstanceModel.nativeDelete(
|
||||
runningInstanceWhere(preview.policy.runningInstanceRetentionDays),
|
||||
)
|
||||
: 0;
|
||||
let cronStats = 0;
|
||||
if (preview.policy.cronStatRetentionDays > 0) {
|
||||
const firstDay = cutoffs.firstDay;
|
||||
cronStats = await CrontabStatModel.destroy({ where: { date: { [Op.lt]: firstDay } }, transaction });
|
||||
await sequelize.query(`INSERT INTO CronStatRetention(id,first_day) VALUES (1,$firstDay)
|
||||
ON CONFLICT(id) DO UPDATE SET first_day=MAX(first_day,excluded.first_day)`,
|
||||
{ bind: { firstDay }, transaction });
|
||||
await sequelize.query(`DELETE FROM CronPrunedUnknownRuns WHERE last_possible_day <
|
||||
(SELECT first_day FROM CronStatRetention WHERE id=1)`, { transaction });
|
||||
}
|
||||
const triggers = preview.policy.runningInstanceRetentionDays > 0
|
||||
? await history.deleteExpired(cutoffs.history, transaction)
|
||||
const cronStats =
|
||||
preview.policy.cronStatRetentionDays > 0
|
||||
? await CrontabStatModel.nativeDelete(
|
||||
cronStatWhere(preview.policy.cronStatRetentionDays),
|
||||
)
|
||||
: 0;
|
||||
if (preview.policy.runningInstanceRetentionDays || preview.policy.cronStatRetentionDays) {
|
||||
// An unbound receipt's day can be wrong. A later bound receipt still
|
||||
// needs the execution-to-task link even after both visible histories expire.
|
||||
// A writer can also win the lock before an interrupted upgrade retries.
|
||||
// Keep its bound bookings until the proof-copy transaction has committed.
|
||||
await sequelize.query(`DELETE FROM CronLegacyExitBookings WHERE day <
|
||||
(SELECT first_day FROM CronStatRetention WHERE id=1)
|
||||
AND NOT EXISTS (SELECT 1 FROM CronTriggers WHERE id=CronLegacyExitBookings.trigger_id)
|
||||
AND ((bound=1 AND EXISTS (SELECT 1 FROM SchemaMigrations WHERE id=$proofMigration))
|
||||
OR (bound=0 AND NOT EXISTS (SELECT 1 FROM Crontabs WHERE id=CronLegacyExitBookings.cron_id)))`,
|
||||
{ bind: { proofMigration: prunedExitMigrationId }, transaction });
|
||||
}
|
||||
return { runningInstances, cronStats, triggers };
|
||||
return { runningInstances, cronStats };
|
||||
});
|
||||
|
||||
const dependenceCaches = [];
|
||||
for (const cache of preview.dependenceCaches) {
|
||||
await fs.rm(path.join(config.dependenceCachePath, cache.type), {
|
||||
@@ -163,14 +118,12 @@ export default class RetentionService {
|
||||
});
|
||||
dependenceCaches.push(cache);
|
||||
}
|
||||
|
||||
if (
|
||||
request.compactDatabase &&
|
||||
(deleted.runningInstances || deleted.cronStats || deleted.triggers)
|
||||
(deleted.runningInstances || deleted.cronStats)
|
||||
) {
|
||||
await sequelize.query('VACUUM');
|
||||
await database.query('VACUUM');
|
||||
}
|
||||
|
||||
return {
|
||||
deleted: {
|
||||
...deleted,
|
||||
@@ -179,7 +132,7 @@ export default class RetentionService {
|
||||
},
|
||||
compactedDatabase: Boolean(
|
||||
request.compactDatabase &&
|
||||
(deleted.runningInstances || deleted.cronStats || deleted.triggers),
|
||||
(deleted.runningInstances || deleted.cronStats),
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import { textSearch } from '../data/queries';
|
||||
import { Query, QuerySpec, orderBy } from '../data/queries';
|
||||
import { Service, Inject } from 'typedi';
|
||||
import winston from 'winston';
|
||||
import config from '../config';
|
||||
@@ -19,7 +21,6 @@ import {
|
||||
rmPath,
|
||||
} from '../config/util';
|
||||
import fs from 'fs/promises';
|
||||
import { FindOptions, Op } from 'sequelize';
|
||||
import path from 'path';
|
||||
import ScheduleService, { TaskCallbacks } from './schedule';
|
||||
import { SimpleIntervalSchedule } from 'toad-scheduler';
|
||||
@@ -42,17 +43,16 @@ import CrontabService from './cron';
|
||||
import taskLimit from '../shared/pLimit';
|
||||
import { logStreamManager } from '../shared/logStreamManager';
|
||||
import { LogReadOptions, readLogChunk } from '../shared/logReader';
|
||||
|
||||
@Service()
|
||||
export default class SubscriptionService {
|
||||
constructor(
|
||||
@Inject('logger') private logger: winston.Logger,
|
||||
@Inject('logger')
|
||||
private logger: winston.Logger,
|
||||
private scheduleService: ScheduleService,
|
||||
private sockService: SockService,
|
||||
private sshKeyService: SshKeyService,
|
||||
private crontabService: CrontabService,
|
||||
) {}
|
||||
|
||||
public async list(
|
||||
searchText?: string,
|
||||
ids?: string,
|
||||
@@ -60,37 +60,23 @@ export default class SubscriptionService {
|
||||
let query = {};
|
||||
const subIds = JSON.parse(ids || '[]');
|
||||
if (searchText) {
|
||||
const reg = {
|
||||
[Op.or]: [
|
||||
{ [Op.like]: `%${searchText}%` },
|
||||
{ [Op.like]: `%${encodeURI(searchText)}%` },
|
||||
],
|
||||
};
|
||||
query = {
|
||||
[Op.or]: [
|
||||
{
|
||||
name: reg,
|
||||
},
|
||||
{
|
||||
url: reg,
|
||||
},
|
||||
],
|
||||
};
|
||||
query = textSearch(['name', 'url'], searchText);
|
||||
}
|
||||
try {
|
||||
const result = await SubscriptionModel.findAll({
|
||||
where: { ...query, ...(ids ? { id: subIds } : undefined) },
|
||||
order: [
|
||||
const result = await SubscriptionModel.find(
|
||||
{ ...query, ...(ids ? { id: subIds } : undefined) },
|
||||
{
|
||||
orderBy: orderBy([
|
||||
['is_disabled', 'ASC'],
|
||||
['createdAt', 'DESC'],
|
||||
],
|
||||
});
|
||||
]),
|
||||
},
|
||||
);
|
||||
return result;
|
||||
} catch (error) {
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
public async handleTask(
|
||||
doc: Subscription,
|
||||
needCreate = true,
|
||||
@@ -101,7 +87,6 @@ export default class SubscriptionService {
|
||||
const { url } = formatUrl(doc);
|
||||
doc.command = formatCommand(doc, url as string);
|
||||
}
|
||||
|
||||
if (doc.schedule_type === 'crontab') {
|
||||
this.scheduleService.cancelCronTask(doc as any);
|
||||
needCreate &&
|
||||
@@ -122,34 +107,34 @@ export default class SubscriptionService {
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
public async setSshConfig() {
|
||||
const docs = await SubscriptionModel.findAll();
|
||||
const docs = await SubscriptionModel.find({}, {});
|
||||
await this.sshKeyService.setSshConfig(docs);
|
||||
}
|
||||
|
||||
private taskCallbacks(doc: Subscription): TaskCallbacks {
|
||||
return {
|
||||
onBefore: async (startTime) => {
|
||||
const logTime = startTime.format('YYYY-MM-DD-HH-mm-ss');
|
||||
const logPath = `${doc.alias}/${logTime}.log`;
|
||||
await SubscriptionModel.update(
|
||||
await SubscriptionModel.nativeUpdate(
|
||||
{ id: doc.id },
|
||||
{
|
||||
status: SubscriptionStatus.running,
|
||||
log_path: logPath,
|
||||
},
|
||||
{ where: { id: doc.id } },
|
||||
);
|
||||
const absolutePath = await handleLogPath(
|
||||
logPath as string,
|
||||
tf('## 开始执行... %s\n', startTime.format('YYYY-MM-DD HH:mm:ss')),
|
||||
);
|
||||
|
||||
// 执行sub_before
|
||||
let beforeStr = '';
|
||||
try {
|
||||
if (doc.sub_before) {
|
||||
await logStreamManager.write(absolutePath, `\n## ${t('执行before命令...')}\n\n`);
|
||||
await logStreamManager.write(
|
||||
absolutePath,
|
||||
`\n## ${t('执行before命令...')}\n\n`,
|
||||
);
|
||||
beforeStr = await promiseExec(doc.sub_before);
|
||||
}
|
||||
} catch (error: any) {
|
||||
@@ -161,11 +146,11 @@ export default class SubscriptionService {
|
||||
}
|
||||
},
|
||||
onStart: async (cp: ChildProcessWithoutNullStreams, startTime) => {
|
||||
await SubscriptionModel.update(
|
||||
await SubscriptionModel.nativeUpdate(
|
||||
{ id: doc.id },
|
||||
{
|
||||
pid: cp.pid,
|
||||
},
|
||||
{ where: { id: doc.id } },
|
||||
);
|
||||
},
|
||||
onEnd: async (cp, endTime, diff) => {
|
||||
@@ -173,7 +158,6 @@ export default class SubscriptionService {
|
||||
try {
|
||||
const sub = await this.getDb({ id: doc.id });
|
||||
absolutePath = await handleLogPath(sub.log_path as string);
|
||||
|
||||
// 执行 sub_after
|
||||
let afterStr = '';
|
||||
try {
|
||||
@@ -186,12 +170,12 @@ export default class SubscriptionService {
|
||||
}
|
||||
} catch (error: any) {
|
||||
afterStr =
|
||||
(error.stderr && error.stderr.toString()) || JSON.stringify(error);
|
||||
(error.stderr && error.stderr.toString()) ||
|
||||
JSON.stringify(error);
|
||||
}
|
||||
if (afterStr) {
|
||||
await logStreamManager.write(absolutePath, `${afterStr}\n`);
|
||||
}
|
||||
|
||||
await logStreamManager.write(
|
||||
absolutePath,
|
||||
'\n' +
|
||||
@@ -206,10 +190,10 @@ export default class SubscriptionService {
|
||||
try {
|
||||
if (absolutePath) await logStreamManager.closeStream(absolutePath);
|
||||
} finally {
|
||||
await SubscriptionModel.update(
|
||||
{ status: SubscriptionStatus.idle, pid: null } as any,
|
||||
{ where: { id: doc.id } },
|
||||
);
|
||||
await SubscriptionModel.nativeUpdate({ id: doc.id }, {
|
||||
status: SubscriptionStatus.idle,
|
||||
pid: null,
|
||||
} as any);
|
||||
this.sockService.sendMessage({
|
||||
type: 'runSubscriptionEnd',
|
||||
message: t('订阅执行完成'),
|
||||
@@ -230,22 +214,19 @@ export default class SubscriptionService {
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
public async create(payload: Subscription): Promise<Subscription> {
|
||||
assertSubscriptionAlias(payload.alias);
|
||||
return withSubscriptionMutation(async () => {
|
||||
const tab = new Subscription(payload);
|
||||
const doc = await this.insert(tab);
|
||||
await this.handleTask(doc.get({ plain: true }));
|
||||
await this.handleTask(doc);
|
||||
await this.setSshConfig();
|
||||
return doc;
|
||||
});
|
||||
}
|
||||
|
||||
public async insert(payload: Subscription): Promise<SubscriptionInstance> {
|
||||
return await SubscriptionModel.create(payload, { returning: true });
|
||||
return await SubscriptionModel.insert(payload);
|
||||
}
|
||||
|
||||
public async update(payload: Subscription): Promise<Subscription> {
|
||||
assertSubscriptionAlias(payload.alias);
|
||||
return withSubscriptionMutation(async () => {
|
||||
@@ -258,7 +239,6 @@ export default class SubscriptionService {
|
||||
return newDoc;
|
||||
});
|
||||
}
|
||||
|
||||
private async removeSshConfigForSubscription(doc: Subscription) {
|
||||
if (doc.type !== 'private-repo' || doc.pull_type !== 'ssh-key') return;
|
||||
// Invalid historical rows must remain deletable without deriving unsafe paths.
|
||||
@@ -269,12 +249,10 @@ export default class SubscriptionService {
|
||||
}
|
||||
await this.sshKeyService.removeSSHKey(doc.alias, '');
|
||||
}
|
||||
|
||||
public async updateDb(payload: Subscription): Promise<Subscription> {
|
||||
await SubscriptionModel.update(payload, { where: { id: payload.id } });
|
||||
await SubscriptionModel.nativeUpdate({ id: payload.id }, payload);
|
||||
return await this.getDb({ id: payload.id });
|
||||
}
|
||||
|
||||
public async status({
|
||||
ids,
|
||||
status,
|
||||
@@ -300,16 +278,16 @@ export default class SubscriptionService {
|
||||
if (last_running_time > 0) {
|
||||
options.last_running_time = last_running_time;
|
||||
}
|
||||
|
||||
return await SubscriptionModel.update(
|
||||
{ ...options },
|
||||
{ where: { id: ids } },
|
||||
);
|
||||
return await SubscriptionModel.nativeUpdate({ id: ids }, { ...options });
|
||||
}
|
||||
|
||||
public async remove(ids: number[], query: { force?: boolean }) {
|
||||
public async remove(
|
||||
ids: number[],
|
||||
query: {
|
||||
force?: boolean;
|
||||
},
|
||||
) {
|
||||
return withSubscriptionMutation(async () => {
|
||||
const docs = await SubscriptionModel.findAll({ where: { id: ids } });
|
||||
const docs = await SubscriptionModel.find({ id: ids }, {});
|
||||
const storagePaths: string[] = [];
|
||||
const retainedPaths: string[] = [];
|
||||
const collectPaths = (
|
||||
@@ -321,7 +299,9 @@ export default class SubscriptionService {
|
||||
// A URL accepted by one engine can produce an invalid name in another.
|
||||
// Validate each candidate independently, retaining the safe candidate.
|
||||
if (!Object.values(names).every(isSubscriptionStorageName)) continue;
|
||||
const resolve = deleting ? resolveSubscriptionStoragePath : path.resolve;
|
||||
const resolve = deleting
|
||||
? resolveSubscriptionStoragePath
|
||||
: path.resolve;
|
||||
const scriptPath = resolve(config.scriptPath, names.script);
|
||||
if (scriptPath) targets.push(scriptPath);
|
||||
if (names.repo) {
|
||||
@@ -329,7 +309,10 @@ export default class SubscriptionService {
|
||||
if (repoPath) targets.push(repoPath);
|
||||
}
|
||||
if (names.raw) {
|
||||
const rawPath = resolve(path.join(config.dataPath, 'raw'), names.raw);
|
||||
const rawPath = resolve(
|
||||
path.join(config.dataPath, 'raw'),
|
||||
names.raw,
|
||||
);
|
||||
if (rawPath) targets.push(rawPath);
|
||||
}
|
||||
}
|
||||
@@ -342,29 +325,29 @@ export default class SubscriptionService {
|
||||
resolveSubscriptionStoragePath(config.repoPath, doc.alias);
|
||||
collectPaths(doc, storagePaths, true);
|
||||
}
|
||||
const remaining = await SubscriptionModel.findAll({ where: {} });
|
||||
const remaining = await SubscriptionModel.find({}, {});
|
||||
for (const doc of remaining) {
|
||||
if (!ids.includes(doc.id!)) collectPaths(doc, retainedPaths);
|
||||
}
|
||||
}
|
||||
for (const doc of docs) {
|
||||
await this.handleTask(doc.get({ plain: true }), false);
|
||||
await this.handleTask(doc, false);
|
||||
}
|
||||
await SubscriptionModel.destroy({ where: { id: ids } });
|
||||
await SubscriptionModel.nativeDelete({ id: ids });
|
||||
for (const doc of docs) {
|
||||
await this.removeSshConfigForSubscription(doc);
|
||||
}
|
||||
await this.setSshConfig();
|
||||
|
||||
if (query?.force === true) {
|
||||
const crons = await CrontabModel.findAll({ where: { sub_id: ids } });
|
||||
const crons = await CrontabModel.find({ sub_id: ids }, {});
|
||||
if (crons?.length) {
|
||||
await this.crontabService.remove(crons.map((x) => x.id!));
|
||||
}
|
||||
for (const storagePath of new Set(storagePaths)) {
|
||||
// rm is recursive: an ancestor must also be retained if a surviving
|
||||
// subscription uses a nested branch, and vice versa.
|
||||
const shared = retainedPaths.some((retained) =>
|
||||
const shared = retainedPaths.some(
|
||||
(retained) =>
|
||||
retained === storagePath ||
|
||||
retained.startsWith(`${storagePath}${path.sep}`) ||
|
||||
storagePath.startsWith(`${retained}${path.sep}`),
|
||||
@@ -374,38 +357,33 @@ export default class SubscriptionService {
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public async getDb(
|
||||
query: FindOptions<Subscription>['where'],
|
||||
): Promise<Subscription> {
|
||||
const doc = await SubscriptionModel.findOne({ where: { ...query } });
|
||||
public async getDb(query: QuerySpec['where']): Promise<Subscription> {
|
||||
const doc = await SubscriptionModel.findOne({ ...query }, {});
|
||||
if (!doc) {
|
||||
throw new Error(`Subscription ${JSON.stringify(query)} not found`);
|
||||
}
|
||||
return doc.get({ plain: true });
|
||||
return doc;
|
||||
}
|
||||
|
||||
public async run(ids: number[]) {
|
||||
await SubscriptionModel.update(
|
||||
await SubscriptionModel.nativeUpdate(
|
||||
{ id: ids },
|
||||
{ status: SubscriptionStatus.queued },
|
||||
{ where: { id: ids } },
|
||||
);
|
||||
ids.forEach((id) => {
|
||||
this.runSingle(id);
|
||||
});
|
||||
}
|
||||
|
||||
public async stop(ids: number[]) {
|
||||
const docs = await SubscriptionModel.findAll({ where: { id: ids } });
|
||||
const docs = await SubscriptionModel.find({ id: ids }, {});
|
||||
let failure: unknown;
|
||||
for (const doc of docs) {
|
||||
try {
|
||||
if (doc.pid) {
|
||||
await killTask(doc.pid, true);
|
||||
}
|
||||
await SubscriptionModel.update(
|
||||
await SubscriptionModel.nativeUpdate(
|
||||
{ id: doc.id, pid: doc.pid ?? null },
|
||||
{ status: SubscriptionStatus.idle, pid: null } as any,
|
||||
{ where: { id: doc.id, pid: doc.pid ?? null } },
|
||||
);
|
||||
} catch (error) {
|
||||
this.logger.error(error);
|
||||
@@ -414,15 +392,12 @@ export default class SubscriptionService {
|
||||
}
|
||||
if (failure) throw failure;
|
||||
}
|
||||
|
||||
private async runSingle(subscriptionId: number) {
|
||||
const subscription = await this.getDb({ id: subscriptionId });
|
||||
if (subscription.status !== SubscriptionStatus.queued) {
|
||||
return;
|
||||
}
|
||||
|
||||
const command = formatCommand(subscription);
|
||||
|
||||
this.scheduleService.runTask(command, this.taskCallbacks(subscription), {
|
||||
name: subscription.name,
|
||||
schedule: subscription.schedule,
|
||||
@@ -431,25 +406,22 @@ export default class SubscriptionService {
|
||||
runOrigin: 'subscription',
|
||||
});
|
||||
}
|
||||
|
||||
public async disabled(ids: number[]) {
|
||||
await SubscriptionModel.update({ is_disabled: 1 }, { where: { id: ids } });
|
||||
const docs = await SubscriptionModel.findAll({ where: { id: ids } });
|
||||
await SubscriptionModel.nativeUpdate({ id: ids }, { is_disabled: 1 });
|
||||
const docs = await SubscriptionModel.find({ id: ids }, {});
|
||||
await this.setSshConfig();
|
||||
for (const doc of docs) {
|
||||
await this.handleTask(doc.get({ plain: true }), false);
|
||||
await this.handleTask(doc, false);
|
||||
}
|
||||
}
|
||||
|
||||
public async enabled(ids: number[]) {
|
||||
await SubscriptionModel.update({ is_disabled: 0 }, { where: { id: ids } });
|
||||
const docs = await SubscriptionModel.findAll({ where: { id: ids } });
|
||||
await SubscriptionModel.nativeUpdate({ id: ids }, { is_disabled: 0 });
|
||||
const docs = await SubscriptionModel.find({ id: ids }, {});
|
||||
await this.setSshConfig();
|
||||
for (const doc of docs) {
|
||||
await this.handleTask(doc.get({ plain: true }));
|
||||
await this.handleTask(doc);
|
||||
}
|
||||
}
|
||||
|
||||
public async log(id: number, options: LogReadOptions = {}) {
|
||||
const doc = await this.getDb({ id });
|
||||
if (!doc || !doc.log_path) {
|
||||
@@ -461,17 +433,14 @@ export default class SubscriptionService {
|
||||
truncated: false,
|
||||
};
|
||||
}
|
||||
|
||||
const absolutePath = await handleLogPath(doc.log_path as string);
|
||||
return await readLogChunk(absolutePath, options);
|
||||
}
|
||||
|
||||
public async logs(id: number) {
|
||||
const doc = await this.getDb({ id });
|
||||
if (!doc) {
|
||||
return [];
|
||||
}
|
||||
|
||||
if (doc.log_path) {
|
||||
const relativeDir = path.dirname(`${doc.log_path}`);
|
||||
const dir = path.dirname(resolveLogPath(config.logPath, doc.log_path));
|
||||
|
||||
+29
-67
@@ -1,3 +1,4 @@
|
||||
import { Query, QuerySpec, orderBy } from '../data/queries';
|
||||
import { persistNotificationAudit } from '../shared/notificationAudit';
|
||||
import { spawn } from 'cross-spawn';
|
||||
import { execFile } from 'child_process';
|
||||
@@ -46,22 +47,16 @@ import os from 'os';
|
||||
import dayjs from 'dayjs';
|
||||
import { t, setLang } from '../shared/i18n';
|
||||
import { updateLinuxMirrorFile } from '../config/util';
|
||||
|
||||
@Service()
|
||||
export default class SystemService {
|
||||
@Inject((type) => NotificationService)
|
||||
private notificationService!: NotificationService;
|
||||
|
||||
constructor(
|
||||
@Inject('logger') private logger: winston.Logger,
|
||||
@Inject('logger')
|
||||
private logger: winston.Logger,
|
||||
private scheduleService: ScheduleService,
|
||||
private sockService: SockService,
|
||||
) {}
|
||||
|
||||
public get cronConcurrency() {
|
||||
return taskLimit.cronConcurrency;
|
||||
}
|
||||
|
||||
public async getSystemConfig() {
|
||||
const doc = await this.getDb({ type: AuthDataType.systemConfig });
|
||||
return {
|
||||
@@ -69,22 +64,19 @@ export default class SystemService {
|
||||
info: { ...doc.info, timezone: doc.info?.timezone || 'Asia/Shanghai' },
|
||||
};
|
||||
}
|
||||
|
||||
private async updateAuthDb(payload: SystemInfo): Promise<SystemInfo> {
|
||||
const { id, ...others } = payload;
|
||||
await SystemModel.update(others, { where: { id } });
|
||||
await SystemModel.nativeUpdate({ id }, others);
|
||||
const doc = await this.getDb({ id });
|
||||
return doc;
|
||||
}
|
||||
|
||||
public async getDb(query: any): Promise<SystemInfo> {
|
||||
const doc = await SystemModel.findOne({ where: query });
|
||||
const doc = await SystemModel.findOne(query, {});
|
||||
if (!doc) {
|
||||
throw new Error(`System ${JSON.stringify(query)} not found`);
|
||||
}
|
||||
return doc.get({ plain: true });
|
||||
return doc;
|
||||
}
|
||||
|
||||
public async updateNotificationMode(notificationInfo: NotificationInfo) {
|
||||
const code = Math.random().toString().slice(-6);
|
||||
const isSuccess = await this.notificationService.testNotify(
|
||||
@@ -102,7 +94,6 @@ export default class SystemService {
|
||||
return { code: 400, message: t('通知发送失败,请检查参数') };
|
||||
}
|
||||
}
|
||||
|
||||
public async updateLogRemoveFrequency(info: SystemModelInfo) {
|
||||
const oDoc = await this.getSystemConfig();
|
||||
const result = await this.updateAuthDb({
|
||||
@@ -129,7 +120,6 @@ export default class SystemService {
|
||||
}
|
||||
return { code: 200, data: info };
|
||||
}
|
||||
|
||||
public async updateCronConcurrency(info: SystemModelInfo) {
|
||||
const limit = info.cronConcurrency ?? 0;
|
||||
if (!Number.isInteger(limit) || limit < 0 || limit > 2147483647) {
|
||||
@@ -146,7 +136,6 @@ export default class SystemService {
|
||||
return { code: 200, data: info };
|
||||
});
|
||||
}
|
||||
|
||||
public async restoreCronConcurrency() {
|
||||
await withSchedulerMutation(async () => {
|
||||
const doc = await this.getSystemConfig();
|
||||
@@ -155,7 +144,6 @@ export default class SystemService {
|
||||
await cronClient.setConcurrency(limit);
|
||||
});
|
||||
}
|
||||
|
||||
public async updateDependenceProxy(info: SystemModelInfo) {
|
||||
const oDoc = await this.getSystemConfig();
|
||||
await this.updateAuthDb({
|
||||
@@ -174,7 +162,6 @@ export default class SystemService {
|
||||
}
|
||||
return { code: 200, data: info };
|
||||
}
|
||||
|
||||
public async updateNodeMirror(info: SystemModelInfo, res?: Response) {
|
||||
const oDoc = await this.getSystemConfig();
|
||||
await this.updateAuthDb({
|
||||
@@ -186,12 +173,13 @@ export default class SystemService {
|
||||
cmd = `pnpm config set registry ${shellQuote(info.nodeMirror)}`;
|
||||
}
|
||||
let command = `cd && ${cmd}`;
|
||||
const docs = await DependenceModel.findAll({
|
||||
where: {
|
||||
const docs = await DependenceModel.find(
|
||||
{
|
||||
type: DependenceTypes.nodejs,
|
||||
status: DependenceStatus.installed,
|
||||
},
|
||||
});
|
||||
{},
|
||||
);
|
||||
if (docs.length > 0) {
|
||||
command += ` && pnpm i -g`;
|
||||
}
|
||||
@@ -223,7 +211,6 @@ export default class SystemService {
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
public async updatePythonMirror(info: SystemModelInfo) {
|
||||
const oDoc = await this.getSystemConfig();
|
||||
await this.updateAuthDb({
|
||||
@@ -237,7 +224,6 @@ export default class SystemService {
|
||||
await promiseExec(cmd);
|
||||
return { code: 200, data: info };
|
||||
}
|
||||
|
||||
public async updateLinuxMirror(
|
||||
info: SystemModelInfo,
|
||||
res?: Response,
|
||||
@@ -284,13 +270,11 @@ export default class SystemService {
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
public async checkUpdate() {
|
||||
const controller = new AbortController();
|
||||
const timeout = setTimeout(() => controller.abort(), 15000);
|
||||
try {
|
||||
const currentVersionContent = await parseVersion(config.versionFile);
|
||||
|
||||
const { body, statusCode } = await request(
|
||||
`${config.lastVersionFile}?t=${Date.now()}`,
|
||||
{ signal: controller.signal },
|
||||
@@ -305,7 +289,6 @@ export default class SystemService {
|
||||
) {
|
||||
throw new Error('Invalid version response');
|
||||
}
|
||||
|
||||
return {
|
||||
code: 200,
|
||||
data: {
|
||||
@@ -327,7 +310,6 @@ export default class SystemService {
|
||||
clearTimeout(timeout);
|
||||
}
|
||||
}
|
||||
|
||||
private checkHasNewVersion(curVersion: string, lastVersion: string) {
|
||||
const curArr = curVersion.split('.').map((x) => parseInt(x, 10));
|
||||
const lastArr = lastVersion.split('.').map((x) => parseInt(x, 10));
|
||||
@@ -346,25 +328,21 @@ export default class SystemService {
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public async updateSystem() {
|
||||
return this.startUpgradeJob('download');
|
||||
}
|
||||
|
||||
private upgradeJobs() {
|
||||
return require(path.join(
|
||||
config.rootPath,
|
||||
'cli/src/internal/maintenance/panelUpgrade.cjs',
|
||||
));
|
||||
}
|
||||
|
||||
public async getUpgradeStatus() {
|
||||
return {
|
||||
code: 200,
|
||||
data: await this.upgradeJobs().getStatus(config.tmpPath),
|
||||
};
|
||||
}
|
||||
|
||||
private async startUpgradeJob(action: 'download' | 'apply') {
|
||||
try {
|
||||
const data = await this.upgradeJobs().startJob(
|
||||
@@ -387,7 +365,6 @@ export default class SystemService {
|
||||
return { code: 400, message: t('升级任务启动失败,请检查日志后重试') };
|
||||
}
|
||||
}
|
||||
|
||||
public async reloadSystem(target?: 'system' | 'data') {
|
||||
if (target && !['system', 'data'].includes(target)) {
|
||||
return { code: 400, message: t('参数错误') };
|
||||
@@ -405,7 +382,6 @@ export default class SystemService {
|
||||
});
|
||||
return { code: 200 };
|
||||
}
|
||||
|
||||
public async notify({
|
||||
title,
|
||||
content,
|
||||
@@ -422,35 +398,38 @@ export default class SystemService {
|
||||
if (notificationInfo && typeString) {
|
||||
notificationInfo.type = typeString;
|
||||
}
|
||||
|
||||
const isSuccess = await this.notificationService.notify(
|
||||
title,
|
||||
content,
|
||||
notificationInfo,
|
||||
);
|
||||
|
||||
if (isSuccess) {
|
||||
return { code: 200, message: t('通知发送成功') };
|
||||
} else {
|
||||
return { code: 400, message: t('通知发送失败,请检查系统设置/通知配置') };
|
||||
}
|
||||
}
|
||||
|
||||
public async recordNotifyLog(info: NotifyLogInfo): Promise<void> {
|
||||
await persistNotificationAudit(info);
|
||||
}
|
||||
|
||||
public async getNotifyLog(): Promise<Array<NotifyLogInfo>> {
|
||||
const docs = await SystemModel.findAll({
|
||||
where: { type: AuthDataType.notifyLog },
|
||||
order: [['id', 'DESC']],
|
||||
const docs = await SystemModel.find(
|
||||
{ type: AuthDataType.notifyLog },
|
||||
{
|
||||
orderBy: orderBy([['id', 'DESC']]),
|
||||
limit: 200,
|
||||
});
|
||||
},
|
||||
);
|
||||
return docs.map((x) => ({ ...x.info, id: x.id }));
|
||||
}
|
||||
|
||||
public async run(
|
||||
{ command, logPath }: { command: string; logPath?: string },
|
||||
{
|
||||
command,
|
||||
logPath,
|
||||
}: {
|
||||
command: string;
|
||||
logPath?: string;
|
||||
},
|
||||
callback: TaskCallbacks,
|
||||
) {
|
||||
if (!command.startsWith(TASK_COMMAND)) {
|
||||
@@ -467,17 +446,14 @@ export default class SystemService {
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
public async stop({ command, pid }: { command: string; pid: number }) {
|
||||
if (!pid && !command) {
|
||||
return { code: 400, message: t('参数错误') };
|
||||
}
|
||||
|
||||
if (pid) {
|
||||
await killTask(pid);
|
||||
return { code: 200 };
|
||||
}
|
||||
|
||||
if (!command.startsWith(TASK_COMMAND)) {
|
||||
command = `${TASK_COMMAND} ${command}`;
|
||||
}
|
||||
@@ -489,7 +465,6 @@ export default class SystemService {
|
||||
return { code: 400, message: t('任务未找到') };
|
||||
}
|
||||
}
|
||||
|
||||
public async exportData(res: Response, type?: string[]) {
|
||||
try {
|
||||
let dataDirs = ['db', 'upload'];
|
||||
@@ -531,7 +506,6 @@ export default class SystemService {
|
||||
return res.send({ code: 400, message: error.message });
|
||||
}
|
||||
}
|
||||
|
||||
public async importData() {
|
||||
try {
|
||||
await promiseExec(`rm -rf ${path.join(config.tmpPath, 'data')}`);
|
||||
@@ -543,7 +517,6 @@ export default class SystemService {
|
||||
return { code: 400, message: error.message };
|
||||
}
|
||||
}
|
||||
|
||||
public async getSystemLog(
|
||||
res: Response,
|
||||
query: {
|
||||
@@ -563,7 +536,6 @@ export default class SystemService {
|
||||
.reverse()
|
||||
.filter((x) => x.title.endsWith('.log'))
|
||||
.filter((x) => x.createTime >= startTime && x.createTime <= endTime);
|
||||
|
||||
const limit = Math.min(
|
||||
Math.max(Number(query.limit) || 1024 * 1024, 1),
|
||||
1024 * 1024,
|
||||
@@ -571,7 +543,10 @@ export default class SystemService {
|
||||
const total = logs.reduce((size, log) => size + (log.size || 0), 0);
|
||||
let remaining = limit;
|
||||
const selected: Array<
|
||||
(typeof logs)[number] & { start: number; length: number }
|
||||
(typeof logs)[number] & {
|
||||
start: number;
|
||||
length: number;
|
||||
}
|
||||
> = [];
|
||||
for (let index = logs.length - 1; index >= 0 && remaining > 0; index--) {
|
||||
const log = logs[index];
|
||||
@@ -582,7 +557,6 @@ export default class SystemService {
|
||||
remaining -= length;
|
||||
}
|
||||
}
|
||||
|
||||
const contentLength = selected.reduce((size, log) => size + log.length, 0);
|
||||
res.set({
|
||||
'Content-Length': contentLength,
|
||||
@@ -594,7 +568,6 @@ export default class SystemService {
|
||||
res.end();
|
||||
return;
|
||||
}
|
||||
|
||||
const currentLog = fileNames.shift();
|
||||
if (currentLog) {
|
||||
const currentFileStream = fs.createReadStream(
|
||||
@@ -611,7 +584,6 @@ export default class SystemService {
|
||||
}
|
||||
})(res, selected);
|
||||
}
|
||||
|
||||
public async deleteSystemLog() {
|
||||
const result = await readDirs(config.systemLogPath, config.systemLogPath);
|
||||
const logs = result.reverse().filter((x) => x.title.endsWith('.log'));
|
||||
@@ -629,7 +601,6 @@ export default class SystemService {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public async updateTimezone(info: SystemModelInfo) {
|
||||
if (!info.timezone) {
|
||||
info.timezone = 'Asia/Shanghai';
|
||||
@@ -646,7 +617,6 @@ export default class SystemService {
|
||||
return { code: 400, message: t('设置时区失败') };
|
||||
}
|
||||
}
|
||||
|
||||
public async updateLanguage(info: SystemModelInfo) {
|
||||
const oDoc = await this.getSystemConfig();
|
||||
const lang = info.lang || 'zh';
|
||||
@@ -666,7 +636,6 @@ export default class SystemService {
|
||||
setLang(lang);
|
||||
return { code: 200, data: { lang } };
|
||||
}
|
||||
|
||||
public async updatePanelTitle(info: SystemModelInfo) {
|
||||
const oDoc = await this.getSystemConfig();
|
||||
const panelTitle = info.panelTitle?.trim() || '';
|
||||
@@ -676,43 +645,36 @@ export default class SystemService {
|
||||
});
|
||||
return { code: 200, data: { panelTitle } };
|
||||
}
|
||||
|
||||
public async updateGlobalSshKey(info: SystemModelInfo) {
|
||||
const oDoc = await this.getSystemConfig();
|
||||
const result = await this.updateAuthDb({
|
||||
...oDoc,
|
||||
info: { ...oDoc.info, ...info },
|
||||
});
|
||||
|
||||
// Apply the global SSH key
|
||||
const SshKeyService = require('./sshKey').default;
|
||||
const Container = require('typedi').Container;
|
||||
const sshKeyService = Container.get(SshKeyService);
|
||||
|
||||
if (info.globalSshKey) {
|
||||
await sshKeyService.addGlobalSSHKey(info.globalSshKey, 'global');
|
||||
} else {
|
||||
await sshKeyService.removeGlobalSSHKey('global');
|
||||
}
|
||||
|
||||
return { code: 200, data: result };
|
||||
}
|
||||
|
||||
public async cleanDependence(type: 'node' | 'python3') {
|
||||
if (!type || !['node', 'python3'].includes(type)) {
|
||||
return { code: 400, message: t('参数错误') };
|
||||
}
|
||||
const finalPath = path.join(config.dependenceCachePath, type);
|
||||
await fs.promises.rm(finalPath, { recursive: true, force: true });
|
||||
await DependenceModel.update(
|
||||
{ status: DependenceStatus.installFailed },
|
||||
await DependenceModel.nativeUpdate(
|
||||
{
|
||||
where: {
|
||||
type:
|
||||
type === 'node' ? DependenceTypes.nodejs : DependenceTypes.python3,
|
||||
status: DependenceStatus.installed,
|
||||
},
|
||||
},
|
||||
{ status: DependenceStatus.installFailed },
|
||||
);
|
||||
return { code: 200 };
|
||||
}
|
||||
|
||||
+20
-71
@@ -34,27 +34,27 @@ import {
|
||||
} from '../shared/password';
|
||||
import { serializeAuthMutation } from '../shared/authMutation';
|
||||
import { LoginThrottle } from '../shared/loginThrottle';
|
||||
|
||||
@Service()
|
||||
export default class UserService {
|
||||
private loginThrottle = new LoginThrottle();
|
||||
@Inject((type) => NotificationService)
|
||||
private notificationService!: NotificationService;
|
||||
|
||||
constructor(
|
||||
@Inject('logger') private logger: winston.Logger,
|
||||
@Inject('logger')
|
||||
private logger: winston.Logger,
|
||||
private scheduleService: ScheduleService,
|
||||
private sockService: SockService,
|
||||
) {}
|
||||
|
||||
@serializeAuthMutation
|
||||
public async login(
|
||||
payloads: { username: string; password: string },
|
||||
payloads: {
|
||||
username: string;
|
||||
password: string;
|
||||
},
|
||||
req: Request,
|
||||
): Promise<any> {
|
||||
return this.authenticate(payloads, req);
|
||||
}
|
||||
|
||||
private async authenticate(
|
||||
payloads: {
|
||||
username: string;
|
||||
@@ -89,7 +89,6 @@ export default class UserService {
|
||||
platform,
|
||||
blockedIps = [],
|
||||
} = content;
|
||||
|
||||
if (
|
||||
ip &&
|
||||
blockedIps.some((blockedIp) => normalizeClientIp(blockedIp) === ip)
|
||||
@@ -107,7 +106,6 @@ export default class UserService {
|
||||
this.getLoginLog();
|
||||
return { code: 403, message: t('该 IP 已被列入黑名单') };
|
||||
}
|
||||
|
||||
const waitTime = this.loginThrottle.retryAfter(ip, timestamp);
|
||||
if (waitTime > 0) {
|
||||
return {
|
||||
@@ -116,10 +114,8 @@ export default class UserService {
|
||||
data: waitTime,
|
||||
};
|
||||
}
|
||||
|
||||
const passwordMatches =
|
||||
username === cUsername && (await verifyPassword(password, cPassword));
|
||||
|
||||
if (passwordMatches && twoFactorActivated && needTwoFactor) {
|
||||
await this.updateAuthInfo(content, {
|
||||
isTwoFactorChecking: true,
|
||||
@@ -130,7 +126,6 @@ export default class UserService {
|
||||
message: '',
|
||||
};
|
||||
}
|
||||
|
||||
if (passwordMatches) {
|
||||
this.loginThrottle.reset(ip);
|
||||
const data = createRandomString(50, 100);
|
||||
@@ -139,7 +134,6 @@ export default class UserService {
|
||||
expiresIn: config.jwt.expiresIn || expiration,
|
||||
algorithm: 'HS384',
|
||||
});
|
||||
|
||||
const tokenInfo: TokenInfo = {
|
||||
value: token,
|
||||
timestamp,
|
||||
@@ -147,13 +141,11 @@ export default class UserService {
|
||||
address,
|
||||
platform: req.platform,
|
||||
};
|
||||
|
||||
const updatedTokens = this.addTokenToList(
|
||||
tokens,
|
||||
req.platform,
|
||||
tokenInfo,
|
||||
);
|
||||
|
||||
await this.updateAuthInfo(content, {
|
||||
password: isPasswordHash(cPassword)
|
||||
? cPassword
|
||||
@@ -252,16 +244,13 @@ export default class UserService {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@serializeAuthMutation
|
||||
public async logout(platform: string, tokenValue: string): Promise<any> {
|
||||
if (!platform || !tokenValue) {
|
||||
this.logger.warn('Invalid logout parameters - empty platform or token');
|
||||
return;
|
||||
}
|
||||
|
||||
const authInfo = await this.getAuthInfo();
|
||||
|
||||
// Verify the token exists before attempting to remove it
|
||||
const tokenExists = this.findTokenInList(
|
||||
authInfo.tokens,
|
||||
@@ -275,45 +264,36 @@ export default class UserService {
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
const updatedTokens = this.removeTokenFromList(
|
||||
authInfo.tokens,
|
||||
platform,
|
||||
tokenValue,
|
||||
);
|
||||
|
||||
await this.updateAuthInfo(authInfo, {
|
||||
token: authInfo.token === tokenValue ? '' : authInfo.token,
|
||||
tokens: updatedTokens,
|
||||
});
|
||||
}
|
||||
|
||||
public async getLoginLog(): Promise<Array<SystemModelInfo | undefined>> {
|
||||
const docs = await SystemModel.findAll({
|
||||
where: { type: AuthDataType.loginLog },
|
||||
});
|
||||
const docs = await SystemModel.find({ type: AuthDataType.loginLog }, {});
|
||||
if (docs && docs.length > 0) {
|
||||
const result = docs.sort(
|
||||
(a, b) => b.info!.timestamp! - a.info!.timestamp!,
|
||||
);
|
||||
if (result.length > 100) {
|
||||
const ids = result.slice(100).map((x) => x.id!);
|
||||
await SystemModel.destroy({
|
||||
where: { id: ids },
|
||||
});
|
||||
await SystemModel.nativeDelete({ id: ids });
|
||||
}
|
||||
return result.map((x) => x.info);
|
||||
}
|
||||
return [];
|
||||
}
|
||||
|
||||
public async getIpBlacklist(): Promise<string[]> {
|
||||
const authInfo = await this.getAuthInfo();
|
||||
return uniq((authInfo.blockedIps || []).map(normalizeClientIp)).filter(
|
||||
Boolean,
|
||||
);
|
||||
}
|
||||
|
||||
@serializeAuthMutation
|
||||
public async blockIp(ip: string): Promise<string[]> {
|
||||
const authInfo = await this.getAuthInfo();
|
||||
@@ -324,7 +304,6 @@ export default class UserService {
|
||||
await this.updateAuthInfo(authInfo, { blockedIps });
|
||||
return blockedIps;
|
||||
}
|
||||
|
||||
@serializeAuthMutation
|
||||
public async unblockIp(ip: string): Promise<string[]> {
|
||||
const authInfo = await this.getAuthInfo();
|
||||
@@ -335,12 +314,10 @@ export default class UserService {
|
||||
await this.updateAuthInfo(authInfo, { blockedIps });
|
||||
return blockedIps;
|
||||
}
|
||||
|
||||
private async insertDb(payload: SystemInfo): Promise<SystemInfo> {
|
||||
const doc = await SystemModel.create({ ...payload }, { returning: true });
|
||||
const doc = await SystemModel.insert({ ...payload });
|
||||
return doc;
|
||||
}
|
||||
|
||||
@serializeAuthMutation
|
||||
public async initializeUser({
|
||||
username,
|
||||
@@ -366,7 +343,6 @@ export default class UserService {
|
||||
});
|
||||
return { code: 200, message: t('更新成功') };
|
||||
}
|
||||
|
||||
@serializeAuthMutation
|
||||
public async updateUsernameAndPassword({
|
||||
username,
|
||||
@@ -389,14 +365,12 @@ export default class UserService {
|
||||
});
|
||||
return { code: 200, message: t('更新成功') };
|
||||
}
|
||||
|
||||
@serializeAuthMutation
|
||||
public async updateAvatar(avatar: string) {
|
||||
const authInfo = await this.getAuthInfo();
|
||||
await this.updateAuthInfo(authInfo, { avatar });
|
||||
return { code: 200, data: avatar, message: t('更新成功') };
|
||||
}
|
||||
|
||||
@serializeAuthMutation
|
||||
public async initTwoFactor() {
|
||||
const secret = authenticator.generateSecret();
|
||||
@@ -408,7 +382,6 @@ export default class UserService {
|
||||
await this.updateAuthInfo(authInfo, { twoFactorSecret: secret });
|
||||
return { secret, url: otpauth };
|
||||
}
|
||||
|
||||
@serializeAuthMutation
|
||||
public async activeTwoFactor(code: string) {
|
||||
const authInfo = await this.getAuthInfo();
|
||||
@@ -427,14 +400,17 @@ export default class UserService {
|
||||
}
|
||||
return isValid;
|
||||
}
|
||||
|
||||
@serializeAuthMutation
|
||||
public async twoFactorLogin(
|
||||
{
|
||||
username,
|
||||
password,
|
||||
code,
|
||||
}: { username: string; password: string; code: string },
|
||||
}: {
|
||||
username: string;
|
||||
password: string;
|
||||
code: string;
|
||||
},
|
||||
req: any,
|
||||
) {
|
||||
const authInfo = await this.getAuthInfo();
|
||||
@@ -482,7 +458,6 @@ export default class UserService {
|
||||
return { code: 430, message: t('验证失败') };
|
||||
}
|
||||
}
|
||||
|
||||
@serializeAuthMutation
|
||||
public async deactivateTwoFactor() {
|
||||
const authInfo = await this.getAuthInfo();
|
||||
@@ -496,7 +471,6 @@ export default class UserService {
|
||||
});
|
||||
return true;
|
||||
}
|
||||
|
||||
public async getAuthInfo() {
|
||||
const authInfo = await shareStore.getAuthInfo();
|
||||
if (authInfo) {
|
||||
@@ -505,7 +479,6 @@ export default class UserService {
|
||||
const doc = await this.getDb({ type: AuthDataType.authConfig });
|
||||
return (doc.info || {}) as AuthInfo;
|
||||
}
|
||||
|
||||
private async updateAuthInfo(authInfo: AuthInfo, info: Partial<AuthInfo>) {
|
||||
const result = { ...authInfo, ...info };
|
||||
await shareStore.updateAuthInfo(result);
|
||||
@@ -517,34 +490,27 @@ export default class UserService {
|
||||
this.sockService.getClients().forEach((conn) => conn.close('401'));
|
||||
}
|
||||
}
|
||||
|
||||
public async getNotificationMode(): Promise<NotificationInfo> {
|
||||
const doc = await this.getDb({ type: AuthDataType.notification });
|
||||
return (doc.info || {}) as NotificationInfo;
|
||||
}
|
||||
|
||||
private async updateAuthDb(payload: SystemInfo): Promise<any> {
|
||||
let doc = await SystemModel.findOne({ where: { type: payload.type } });
|
||||
let doc = await SystemModel.findOne({ type: payload.type }, {});
|
||||
if (doc) {
|
||||
const updateResult = await SystemModel.update(payload, {
|
||||
where: { id: doc.id },
|
||||
returning: true,
|
||||
});
|
||||
doc = updateResult[1][0];
|
||||
await SystemModel.nativeUpdate({ id: doc.id }, payload);
|
||||
doc = await SystemModel.findOne({ id: doc.id });
|
||||
} else {
|
||||
doc = await SystemModel.create(payload, { returning: true });
|
||||
doc = await SystemModel.insert(payload);
|
||||
}
|
||||
return doc;
|
||||
}
|
||||
|
||||
public async getDb(query: any): Promise<SystemInfo> {
|
||||
const doc = await SystemModel.findOne({ where: { ...query } });
|
||||
const doc = await SystemModel.findOne({ ...query }, {});
|
||||
if (!doc) {
|
||||
throw new Error(`${JSON.stringify(query)} not found`);
|
||||
}
|
||||
return doc.get({ plain: true });
|
||||
return doc;
|
||||
}
|
||||
|
||||
public async updateNotificationMode(notificationInfo: NotificationInfo) {
|
||||
const code = Math.random().toString().slice(-6);
|
||||
const isSuccess = await this.notificationService.testNotify(
|
||||
@@ -562,12 +528,10 @@ export default class UserService {
|
||||
return { code: 400, message: t('通知发送失败,请检查参数') };
|
||||
}
|
||||
}
|
||||
|
||||
private normalizeTokens(
|
||||
tokens: Record<string, string | TokenInfo[]>,
|
||||
): Record<string, TokenInfo[]> {
|
||||
const normalized: Record<string, TokenInfo[]> = {};
|
||||
|
||||
for (const [platform, value] of Object.entries(tokens)) {
|
||||
if (typeof value === 'string') {
|
||||
// Legacy format: convert string token to TokenInfo array
|
||||
@@ -589,10 +553,8 @@ export default class UserService {
|
||||
normalized[platform] = value || [];
|
||||
}
|
||||
}
|
||||
|
||||
return normalized;
|
||||
}
|
||||
|
||||
private addTokenToList(
|
||||
tokens: Record<string, string | TokenInfo[]>,
|
||||
platform: string,
|
||||
@@ -606,16 +568,12 @@ export default class UserService {
|
||||
);
|
||||
maxTokensPerPlatform = config.maxTokensPerPlatform;
|
||||
}
|
||||
|
||||
const normalized = this.normalizeTokens(tokens);
|
||||
|
||||
if (!normalized[platform]) {
|
||||
normalized[platform] = [];
|
||||
}
|
||||
|
||||
// Add new token
|
||||
normalized[platform].unshift(tokenInfo);
|
||||
|
||||
// Limit the number of active tokens per platform
|
||||
if (normalized[platform].length > maxTokensPerPlatform) {
|
||||
normalized[platform] = normalized[platform].slice(
|
||||
@@ -623,40 +581,32 @@ export default class UserService {
|
||||
maxTokensPerPlatform,
|
||||
);
|
||||
}
|
||||
|
||||
return normalized;
|
||||
}
|
||||
|
||||
private removeTokenFromList(
|
||||
tokens: Record<string, string | TokenInfo[]>,
|
||||
platform: string,
|
||||
tokenValue: string,
|
||||
): Record<string, TokenInfo[]> {
|
||||
const normalized = this.normalizeTokens(tokens);
|
||||
|
||||
if (normalized[platform]) {
|
||||
normalized[platform] = normalized[platform].filter(
|
||||
(t) => t.value !== tokenValue,
|
||||
);
|
||||
}
|
||||
|
||||
return normalized;
|
||||
}
|
||||
|
||||
private findTokenInList(
|
||||
tokens: Record<string, string | TokenInfo[]>,
|
||||
platform: string,
|
||||
tokenValue: string,
|
||||
): TokenInfo | undefined {
|
||||
const normalized = this.normalizeTokens(tokens);
|
||||
|
||||
if (normalized[platform]) {
|
||||
return normalized[platform].find((t) => t.value === tokenValue);
|
||||
}
|
||||
|
||||
return undefined;
|
||||
}
|
||||
|
||||
@serializeAuthMutation
|
||||
public async resetAuthInfo(info: Partial<AuthInfo>) {
|
||||
const { retries, twoFactorActivated, password, username } = info;
|
||||
@@ -673,7 +623,6 @@ export default class UserService {
|
||||
},
|
||||
(x) => !isNil(x),
|
||||
);
|
||||
|
||||
if (password !== undefined) {
|
||||
payload.password = await hashPassword(password);
|
||||
}
|
||||
|
||||
@@ -1,62 +0,0 @@
|
||||
import os from 'os';
|
||||
import { readFileSync } from 'fs';
|
||||
import path from 'path';
|
||||
|
||||
function read(file: string): string {
|
||||
try { return readFileSync(file, 'utf8').trim(); } catch { return ''; }
|
||||
}
|
||||
|
||||
// Walk ancestors too: a nested cgroup can inherit a tighter parent quota.
|
||||
export function containerResources(readValue = read, platform = process.platform) {
|
||||
const hostCpus = os.cpus().length;
|
||||
const hostMemory = os.totalmem();
|
||||
let cpus = hostCpus;
|
||||
let memTotal = hostMemory;
|
||||
let memFree = os.freemem();
|
||||
if (platform === 'linux') {
|
||||
const groups = readValue('/proc/self/cgroup').split('\n');
|
||||
for (const line of groups) {
|
||||
const match = /^\d+:([^:]*):(\/.*)$/.exec(line);
|
||||
if (!match) continue;
|
||||
const controllers = match[1].split(',');
|
||||
const unified = !match[1];
|
||||
for (const kind of ['cpu', 'memory', 'cpuset']) {
|
||||
if (!unified && !controllers.includes(kind)) continue;
|
||||
const roots = unified ? ['/sys/fs/cgroup'] : [...new Set([kind, match[1]].map(k => '/sys/fs/cgroup/' + k))];
|
||||
for (const root of roots) {
|
||||
let dir = path.join(root, path.normalize(match[2]));
|
||||
while (dir === root || dir.startsWith(root + '/')) {
|
||||
const value = (file: string) => readValue(path.join(dir, file));
|
||||
if (kind === 'cpu') {
|
||||
const [quota, period] = (unified ? value('cpu.max').split(/\s+/) :
|
||||
[value('cpu.cfs_quota_us'), value('cpu.cfs_period_us')]).map(Number);
|
||||
if (quota > 0 && period > 0) cpus = Math.min(cpus, quota / period);
|
||||
} else if (kind === 'cpuset') {
|
||||
const set = value(unified ? 'cpuset.cpus.effective' : 'cpuset.cpus');
|
||||
if (/^\d+(?:-\d+)?(?:,\d+(?:-\d+)?)*$/.test(set)) {
|
||||
const count = set.split(',').reduce((n, range) => {
|
||||
const [lo, hi] = range.split('-').map(Number);
|
||||
return n + (hi ?? lo) - lo + 1;
|
||||
}, 0);
|
||||
if (count > 0) cpus = Math.min(cpus, count);
|
||||
}
|
||||
} else {
|
||||
const limit = Number(value(unified ? 'memory.max' : 'memory.limit_in_bytes'));
|
||||
if (limit > 0 && limit <= memTotal) {
|
||||
const usage = value(unified ? 'memory.current' : 'memory.usage_in_bytes');
|
||||
if (usage && Number.isFinite(Number(usage))) {
|
||||
memTotal = limit;
|
||||
memFree = Math.max(0, limit - Number(usage));
|
||||
}
|
||||
}
|
||||
}
|
||||
if (dir === root) break;
|
||||
dir = path.dirname(dir);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return { cpus, memTotal, memFree, hostCpus, hostMemory,
|
||||
memUsagePercent: ((1 - memFree / memTotal) * 100).toFixed(1) };
|
||||
}
|
||||
@@ -1,35 +0,0 @@
|
||||
import { join } from 'path';
|
||||
import { existsSync } from 'fs';
|
||||
import { receiptPath } from './managedExit.cjs';
|
||||
import { spawn } from 'cross-spawn';
|
||||
import type { ChildProcessWithoutNullStreams } from 'child_process';
|
||||
import type { Readable } from 'stream';
|
||||
|
||||
// A managed command waits on its parent's pipe. EOF before authorization exits
|
||||
// without interpreting the command, even when the worker is killed by SIGKILL.
|
||||
export function spawnCronCommand(command: string, triggerId?: string, onCommandStart?: (at: number) => void) {
|
||||
if (!triggerId) return spawn(command, { shell: '/bin/bash' });
|
||||
const sourceScript = join(__dirname, '../../shell/cron-command.py');
|
||||
const supervisor = existsSync(sourceScript) ? sourceScript : join(process.env.QL_DIR!, 'shell/cron-command.py');
|
||||
const args = ['-I', '-S', supervisor, command, String(process.pid),
|
||||
receiptPath(triggerId) || '', process.execPath, join(__dirname, 'managedExit.cjs'),
|
||||
];
|
||||
if (onCommandStart) args.push('report-start');
|
||||
const child = spawn('python3', args, { env: { ...process.env, QL_TRIGGER_ID: triggerId },
|
||||
stdio: onCommandStart ? ['pipe', 'pipe', 'pipe', 'pipe'] : 'pipe' }) as ChildProcessWithoutNullStreams;
|
||||
if (onCommandStart && child.stdio[3]) {
|
||||
const timing = child.stdio[3] as Readable;
|
||||
let stamp = '';
|
||||
timing.setEncoding('ascii').on('data', chunk => { stamp += chunk; });
|
||||
timing.once('end', () => { if (/^\d{13}$/.test(stamp)) onCommandStart(Number(stamp)); });
|
||||
timing.on('error', () => {}); // Missing telemetry must not change the command result.
|
||||
}
|
||||
// A concurrent stop can close the pipe before the authorization write.
|
||||
child.stdin.on('error', () => {});
|
||||
return child;
|
||||
}
|
||||
|
||||
export function releaseCronCommand(child: ChildProcessWithoutNullStreams): Promise<void> {
|
||||
return new Promise((resolve, reject) =>
|
||||
child.stdin.end('run\n', (error?: Error) => error ? reject(error) : resolve()));
|
||||
}
|
||||
@@ -1,39 +0,0 @@
|
||||
// Read literal shell words only. Never expand or execute a command to derive a
|
||||
// path. Adjacent quoted/unquoted fragments belong to the same argument.
|
||||
function words(command: string): string[] {
|
||||
const result: string[] = [];
|
||||
let value = '', quote = '', active = false;
|
||||
for (let i = 0; i < command.length; i++) {
|
||||
const c = command[i];
|
||||
if (quote && c === quote) { quote = ''; continue; }
|
||||
if (!quote && (c === "'" || c === '"')) { quote = c; active = true; continue; }
|
||||
if (c === '\\' && quote !== "'") {
|
||||
const next = command[++i];
|
||||
if (next === undefined) return [];
|
||||
if (quote === '"' && !/[$`"\\\n]/.test(next)) value += '\\';
|
||||
if (next !== '\n') { value += next; active = true; }
|
||||
continue;
|
||||
}
|
||||
if (!quote && /[;&|<>()\n]/.test(c)) break;
|
||||
if (!quote && /\s/.test(c)) {
|
||||
if (active) result.push(value);
|
||||
value = ''; active = false; continue;
|
||||
}
|
||||
if (!active && !quote && c === '#') break;
|
||||
value += c; active = true;
|
||||
}
|
||||
if (quote) return [];
|
||||
if (active) result.push(value);
|
||||
return result;
|
||||
}
|
||||
|
||||
export function cronOperand(command: string, taskOnly = false): string | undefined {
|
||||
const args = words(command.trim());
|
||||
if (args[0] === 'task') args.shift();
|
||||
else if (taskOnly && args[0] === 'ql') return;
|
||||
while (args[0] === '-l' || args[0] === '-m') {
|
||||
if (args.shift() === '-m') args.shift();
|
||||
}
|
||||
if (args.length > 1 && /^(?:.*\/)?(?:node|python3?|bash|sh|ts-node(?:-transpile-only)?)$/.test(args[0])) args.shift();
|
||||
return args[0];
|
||||
}
|
||||
@@ -1,53 +0,0 @@
|
||||
import { upcomingSlots } from './cronScheduler';
|
||||
|
||||
type Definition = {
|
||||
schedule?: string;
|
||||
extra_schedules?: { schedule: string }[];
|
||||
isDisabled?: number;
|
||||
saved?: boolean;
|
||||
};
|
||||
const cache = new Map<string, { after: number; times: number[] }>();
|
||||
|
||||
export function previewSchedule(
|
||||
schedule: string,
|
||||
count: number,
|
||||
now: number,
|
||||
): number[] {
|
||||
const key = JSON.stringify([
|
||||
Intl.DateTimeFormat().resolvedOptions().timeZone,
|
||||
schedule,
|
||||
]);
|
||||
const cached = cache.get(key);
|
||||
if (cached && now >= cached.after) {
|
||||
const future = cached.times.filter((time) => time > now);
|
||||
if (future.length >= count) return future.slice(0, count);
|
||||
}
|
||||
const times = upcomingSlots(schedule, now, count);
|
||||
if (cache.size >= 512) cache.delete(cache.keys().next().value!);
|
||||
cache.set(key, { after: now, times });
|
||||
return times;
|
||||
}
|
||||
|
||||
export function withNextRun<T extends Definition>(cron: T) {
|
||||
let nextRunTime: number | null = null;
|
||||
if (
|
||||
cron.schedule &&
|
||||
!cron.isDisabled &&
|
||||
cron.saved !== false &&
|
||||
!cron.schedule.startsWith('@once') &&
|
||||
!cron.schedule.startsWith('@boot')
|
||||
) {
|
||||
try {
|
||||
const now = Date.now();
|
||||
nextRunTime = Math.min(
|
||||
...[
|
||||
cron.schedule,
|
||||
...(cron.extra_schedules || []).map((x) => x.schedule),
|
||||
].map((rule) => previewSchedule(rule, 1, now)[0]),
|
||||
);
|
||||
} catch {
|
||||
// Legacy invalid rows remain visible and editable.
|
||||
}
|
||||
}
|
||||
return { ...cron, nextRunTime };
|
||||
}
|
||||
@@ -1,172 +0,0 @@
|
||||
import { readFileSync } from 'fs';
|
||||
import { execFileSync, spawnSync } from 'child_process';
|
||||
|
||||
// Legacy runs can outlive a scheduler restart without an active trigger receipt.
|
||||
export function hasLiveCronProcess(status?: number, pid?: number | null) {
|
||||
if (status !== 0 || !pid || pid < 0) return false; // CrontabStatus.running
|
||||
try {
|
||||
process.kill(pid, 0);
|
||||
return true;
|
||||
} catch (error) {
|
||||
const code = (error as NodeJS.ErrnoException).code;
|
||||
if (code === 'ESRCH') return false;
|
||||
if (code === 'EPERM') return true;
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
function readBsdProcessField(pid: number, field: 'lstart' | 'ppid') {
|
||||
const result = spawnSync('ps', ['-p', String(pid), '-o', field + '='], {
|
||||
encoding: 'utf8', env: { ...process.env, LC_ALL: 'C', TZ: 'UTC' },
|
||||
});
|
||||
// ENOENT from spawning ps refers to the executable, not the target PID.
|
||||
if (result.error) throw new Error('Cannot run ps: ' + result.error.message, { cause: result.error });
|
||||
const value = result.stdout.trim();
|
||||
if (result.status === 0 && value) return value;
|
||||
// BSD ps exits 1 without output when the selected PID has already exited.
|
||||
if (result.status === 1 && !value && !result.stderr.trim())
|
||||
throw Object.assign(new Error('Process has exited'), { code: 'ESRCH' });
|
||||
throw new Error(`Cannot read ${field} for PID ${pid}: ${result.stderr.trim() || result.signal || 'ps status ' + result.status}`);
|
||||
}
|
||||
|
||||
export function systemOwner(pid: number) {
|
||||
if (process.platform !== 'linux') {
|
||||
// BSD crontab installations have no procfs. ps exposes the process birth time.
|
||||
process.kill(pid, 0);
|
||||
const birth = readBsdProcessField(pid, 'lstart');
|
||||
return `crond:${pid}:${birth}`;
|
||||
}
|
||||
const stat = readFileSync(`/proc/${pid}/stat`, 'utf8');
|
||||
const fields = stat.slice(stat.lastIndexOf(')') + 2).split(' ');
|
||||
if (['Z', 'X', 'x'].includes(fields[0])) throw Object.assign(new Error('Process has exited'), { code: 'ESRCH' });
|
||||
const startTicks = fields[19];
|
||||
const boot = readFileSync('/proc/sys/kernel/random/boot_id', 'utf8').trim();
|
||||
return `crond:${pid}:${startTicks}:${boot}`;
|
||||
}
|
||||
|
||||
let linuxClockTicks: number | undefined;
|
||||
|
||||
// A start packet may arrive after its PID was recycled, before the replacement reports.
|
||||
export function legacyProcessOwner(pid: number, started: number): string | undefined {
|
||||
try {
|
||||
const identity = systemOwner(pid);
|
||||
const birth = identity.slice(`crond:${pid}:`.length);
|
||||
let bornAt: number;
|
||||
if (process.platform === 'linux') {
|
||||
linuxClockTicks ??= Number(execFileSync('getconf', ['CLK_TCK'], { encoding: 'utf8' }));
|
||||
const boot = /^btime (\d+)$/m.exec(readFileSync('/proc/stat', 'utf8'));
|
||||
if (!boot || !(linuxClockTicks > 0)) throw new Error('Cannot read process birth time');
|
||||
bornAt = Number(boot[1]) + Number(birth.split(':')[0]) / linuxClockTicks;
|
||||
} else {
|
||||
bornAt = Date.parse(birth + ' UTC') / 1000;
|
||||
}
|
||||
// Both the callback and Linux boot time have one-second precision.
|
||||
return Math.floor(bornAt) <= started + 1 ? identity : undefined;
|
||||
} catch (error) {
|
||||
if (['ESRCH', 'ENOENT'].includes((error as NodeJS.ErrnoException).code!)) return undefined;
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
// PID 1 survives worker restarts, but changes when a container or Linux host restarts.
|
||||
export function pidNamespaceOwner() {
|
||||
return process.platform === 'linux' ? systemOwner(1) : null;
|
||||
}
|
||||
|
||||
// psTree enumerates asynchronously. Reject a PID already reparented or recycled
|
||||
// between enumeration and the birth-token snapshot.
|
||||
export function isProcessDescendant(pid: number, root: number) {
|
||||
const seen = new Set<number>();
|
||||
while (pid > 1 && !seen.has(pid)) {
|
||||
if (pid === root) return true;
|
||||
seen.add(pid);
|
||||
if (process.platform === 'linux') {
|
||||
const stat = readFileSync(`/proc/${pid}/stat`, 'utf8');
|
||||
pid = Number(stat.slice(stat.lastIndexOf(')') + 2).split(' ')[1]);
|
||||
} else {
|
||||
pid = Number(readBsdProcessField(pid, 'ppid'));
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// For an individual legacy instance the task ID alone also matches its siblings.
|
||||
export function verifyCronProcess(pid: number, cronId: number, identity?: string | null, started?: number,
|
||||
instance?: { logPath?: string }) {
|
||||
const conflict = () => Object.assign(new Error('Task process identity could not be verified'), { status: 409 });
|
||||
if (!Number.isInteger(pid) || pid <= 1) throw conflict();
|
||||
if (identity) {
|
||||
// A birth token for this PID proves the original process is gone if the
|
||||
// kernel now reports a different birth. Access errors remain retryable.
|
||||
if (!identity.startsWith(`crond:${pid}:`)) throw conflict();
|
||||
let current: string;
|
||||
try { current = systemOwner(pid); }
|
||||
catch (error) {
|
||||
if ((error as NodeJS.ErrnoException).code === 'ENOENT')
|
||||
throw Object.assign(new Error('Command already exited'), { code: 'ESRCH' });
|
||||
throw error;
|
||||
}
|
||||
if (current !== identity) throw Object.assign(new Error('Command PID was reused'), { code: 'PID_REUSED', status: 409 });
|
||||
return current;
|
||||
}
|
||||
try {
|
||||
if (process.platform === 'linux') {
|
||||
const env = readFileSync(`/proc/${pid}/environ`, 'utf8').split('\0');
|
||||
if (instance && (!instance.logPath || instance.logPath === '/dev/null' ||
|
||||
!env.includes('real_log_path=' + instance.logPath))) throw conflict();
|
||||
if (env.includes('ID=' + cronId) && started) {
|
||||
const boot = /^btime (\d+)$/m.exec(readFileSync('/proc/stat', 'utf8'));
|
||||
const birth = systemOwner(pid);
|
||||
const ticks = Number(birth.split(':')[2]);
|
||||
const hz = Number(execFileSync('getconf', ['CLK_TCK'], { encoding: 'utf8' }));
|
||||
if (boot && hz > 0 && Math.floor(Number(boot[1]) + ticks / hz) <= started + 1) return birth;
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
if (['ENOENT', 'ESRCH'].includes((error as NodeJS.ErrnoException).code!)) {
|
||||
// Distinguish a completed child whose receipt is still being written
|
||||
// from a live PID with an unverifiable identity.
|
||||
try { systemOwner(pid); } catch (probe) {
|
||||
if (['ENOENT', 'ESRCH'].includes((probe as NodeJS.ErrnoException).code!))
|
||||
throw Object.assign(new Error('Command already exited'), { code: 'ESRCH' });
|
||||
}
|
||||
}
|
||||
}
|
||||
throw conflict();
|
||||
}
|
||||
|
||||
// After a stop worker exits, descendants may already have been adopted by PID 1.
|
||||
// A saved birth identity still identifies them; walking the dead root no longer can.
|
||||
export async function finishStoppedTree(identities: string[], signalledAt?: number | null) {
|
||||
const surviving = () => identities.flatMap(identity => {
|
||||
const pid = Number(identity.split(':')[1]);
|
||||
if (!Number.isSafeInteger(pid) || pid <= 1) throw new Error('Invalid saved process identity');
|
||||
try { return systemOwner(pid) === identity ? [pid] : []; }
|
||||
catch (error) {
|
||||
if (['ESRCH', 'ENOENT'].includes((error as NodeJS.ErrnoException).code!)) return [];
|
||||
throw error;
|
||||
}
|
||||
});
|
||||
const remainingGrace = Math.min(1000, Math.max(0, (signalledAt ?? Date.now()) + 1000 - Date.now()));
|
||||
const graceDeadline = Date.now() + remainingGrace;
|
||||
while (surviving().length) {
|
||||
const remaining = graceDeadline - Date.now();
|
||||
if (remaining <= 0) break;
|
||||
await new Promise(resolve => setTimeout(resolve, Math.min(20, remaining)));
|
||||
}
|
||||
if (!surviving().length) return;
|
||||
// Revalidate each PID immediately before signalling, including after the grace period.
|
||||
for (const identity of identities) {
|
||||
const pid = Number(identity.split(':')[1]);
|
||||
try {
|
||||
if (systemOwner(pid) === identity) process.kill(pid, 'SIGKILL');
|
||||
} catch (error) {
|
||||
if (!['ESRCH', 'ENOENT'].includes((error as NodeJS.ErrnoException).code!)) throw error;
|
||||
}
|
||||
}
|
||||
const deadline = Date.now() + 1000;
|
||||
while (surviving().length) {
|
||||
if (Date.now() >= deadline) throw new Error('Stopped process tree did not exit');
|
||||
await new Promise(resolve => setTimeout(resolve, 20));
|
||||
}
|
||||
}
|
||||
@@ -1,23 +0,0 @@
|
||||
import { upcomingSlots } from './cronScheduler';
|
||||
|
||||
// Find only the latest eligible slot even for a second-level rule after hours
|
||||
// offline. Search by time, so cost is logarithmic in the configured window.
|
||||
export function latestMissedSlot(
|
||||
schedule: string,
|
||||
since: number,
|
||||
until: number,
|
||||
): number | null {
|
||||
let low = Math.floor(since / 1000);
|
||||
let high = Math.floor(until / 1000);
|
||||
let latest: number | null = null;
|
||||
while (low < high) {
|
||||
const middle = Math.floor((low + high) / 2);
|
||||
const [next] = upcomingSlots(schedule, middle * 1000);
|
||||
if (next > until) high = middle;
|
||||
else {
|
||||
latest = next;
|
||||
low = next / 1000;
|
||||
}
|
||||
}
|
||||
return latest;
|
||||
}
|
||||
@@ -135,8 +135,10 @@ export function parseCronSchedule(schedule: unknown): CronSchedule {
|
||||
};
|
||||
Object.freeze(patterns);
|
||||
Object.freeze(parsed);
|
||||
if (scheduleCache.size >= 512)
|
||||
scheduleCache.delete(scheduleCache.keys().next().value);
|
||||
if (scheduleCache.size >= 512) {
|
||||
const oldest = scheduleCache.keys().next().value;
|
||||
if (oldest !== undefined) scheduleCache.delete(oldest);
|
||||
}
|
||||
scheduleCache.set(cacheKey, parsed);
|
||||
return parsed;
|
||||
}
|
||||
|
||||
@@ -12,17 +12,6 @@ export interface CronJob {
|
||||
cancel(): void;
|
||||
}
|
||||
|
||||
function acceptsSlot(parsed: ReturnType<typeof parseCronSchedule>, tasks: ScheduledTask[], index: number, date: Date) {
|
||||
if (tasks.length === 1) return true;
|
||||
// Preserve cron-parser 4's day/weekday OR semantics, including its
|
||||
// month-dependent full-day range and the global nth-week constraint.
|
||||
if (parsed.nthDay && Math.ceil(date.getDate() / 7) !== parsed.nthDay)
|
||||
return false;
|
||||
if (index === 1) return !tasks[0].match(date);
|
||||
const monthDays = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
|
||||
return parsed.dayCount < monthDays[date.getMonth()] || tasks[1].match(date);
|
||||
}
|
||||
|
||||
// node-cron owns timers and calendar calculation; Qinglong owns execution
|
||||
// concurrency and process lifetime. Missed in-process slots join that same queue.
|
||||
export function createCronJob(
|
||||
@@ -34,8 +23,18 @@ export function createCronJob(
|
||||
const tasks: ScheduledTask[] = [];
|
||||
let cancelled = false;
|
||||
let started = false;
|
||||
const accepts = (index: number, date: Date) => {
|
||||
if (tasks.length === 1) return true;
|
||||
// Preserve cron-parser 4's day/weekday OR semantics, including its
|
||||
// month-dependent full-day range and the global nth-week constraint.
|
||||
if (parsed.nthDay && Math.ceil(date.getDate() / 7) !== parsed.nthDay)
|
||||
return false;
|
||||
if (index === 1) return !tasks[0].match(date);
|
||||
const monthDays = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
|
||||
return parsed.dayCount < monthDays[date.getMonth()] || tasks[1].match(date);
|
||||
};
|
||||
const dispatch = async (index: number, date: Date, missed: boolean) => {
|
||||
if (cancelled || !started || !acceptsSlot(parsed, tasks, index, date)) return;
|
||||
if (cancelled || !started || !accepts(index, date)) return;
|
||||
if (missed) {
|
||||
options.logger.warn(
|
||||
t('[schedule][补执行迟到任务] 任务: %s, 计划时间: %s'),
|
||||
@@ -89,54 +88,3 @@ export function createCronJob(
|
||||
if (options.start !== false) job.start();
|
||||
return job;
|
||||
}
|
||||
|
||||
|
||||
// node-cron 4.6.0 exposes getNextRuns only from the wall clock. Its pinned
|
||||
// inline matcher also accepts an explicit cursor, needed for previews and recovery.
|
||||
export function upcomingSlots(schedule: string, after: number, count = 1, through?: number): number[] {
|
||||
const parsed = parseCronSchedule(schedule);
|
||||
const tasks: ScheduledTask[] = [];
|
||||
try {
|
||||
const matchers = parsed.patterns.map((pattern) => {
|
||||
const task = createTask(pattern, () => {});
|
||||
tasks.push(task);
|
||||
return (task as ScheduledTask & {
|
||||
timeMatcher: { getNextMatch(date: Date): Date; expressions: number[][] };
|
||||
}).timeMatcher;
|
||||
});
|
||||
const next = matchers.map((matcher) => matcher.getNextMatch(new Date(after)));
|
||||
// All calendar branches share their clock fields. For bounded audit ranges,
|
||||
// resolve each matching minute once, including the matcher's DST choice.
|
||||
const seconds = through == null ? [] : [...new Set(matchers[0].expressions[0])].sort((a,b) => a-b);
|
||||
const slots: number[] = [];
|
||||
let horizon = after + 366 * 100 * 86400000;
|
||||
while (slots.length < count) {
|
||||
const time = Math.min(...next.map(Number));
|
||||
if (through != null && time > through) break;
|
||||
if (!Number.isFinite(time) || time > horizon) throw new Error('No matching calendar date');
|
||||
let accepted = false;
|
||||
next.forEach((date, index) => {
|
||||
if (+date !== time) return;
|
||||
const valid = acceptsSlot(parsed, tasks, index, date);
|
||||
accepted ||= valid;
|
||||
// Both branches share the clock fields. Rejection applies to the
|
||||
// entire local day, including schedules that fire every second.
|
||||
const cursor = new Date(time);
|
||||
if (!valid) cursor.setHours(23, 59, 59, 999);
|
||||
else if (through != null) cursor.setTime(time - time % 60000 + 59999);
|
||||
next[index] = matchers[index].getNextMatch(cursor);
|
||||
});
|
||||
if (accepted) {
|
||||
if (through == null) slots.push(time);
|
||||
else for (const second of seconds) {
|
||||
const slot = time - time % 60000 + second * 1000;
|
||||
if (slot >= time && slot <= through && slots.length < count) slots.push(slot);
|
||||
}
|
||||
horizon = time + 366 * 100 * 86400000;
|
||||
}
|
||||
}
|
||||
return slots;
|
||||
} finally {
|
||||
tasks.forEach((task) => task.destroy());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,57 +0,0 @@
|
||||
import dayjs from 'dayjs';
|
||||
import { QueryTypes, Sequelize, Transaction } from 'sequelize';
|
||||
|
||||
// Hold the receipt claim and the daily increment in the same write transaction.
|
||||
export async function recordCronResult(
|
||||
database: Sequelize, cronId: number, _code: number, elapsedMs: number,
|
||||
finishedAt: number, triggerId: string, transaction?: Transaction,
|
||||
): Promise<void> {
|
||||
if (!triggerId) throw new Error('Execution identity required');
|
||||
if (!transaction) {
|
||||
return database.transaction((tx) =>
|
||||
recordCronResult(database, cronId, _code, elapsedMs, finishedAt, triggerId, tx));
|
||||
}
|
||||
const bind = { ref: cronId, id: triggerId };
|
||||
const claimed = await database.query(
|
||||
"UPDATE CronTriggers SET counted=1,exit_pending=NULL WHERE cron_id=$ref AND id=$id AND counted=0 AND started_at IS NOT NULL AND state IN ('finished','failed','stopped')",
|
||||
{ bind, type: QueryTypes.BULKUPDATE, transaction },
|
||||
);
|
||||
if (!claimed) {
|
||||
const rows = await database.query('SELECT 1 FROM CronTriggers WHERE cron_id=$ref AND id=$id',
|
||||
{ bind, type: QueryTypes.SELECT, transaction });
|
||||
if (!rows.length) throw new Error('Unknown trigger');
|
||||
return;
|
||||
}
|
||||
const [receipt] = await database.query<{ state: string; finished_at: number; reversible: number }>(
|
||||
`SELECT state,finished_at,EXISTS(SELECT 1 FROM CronLegacyExitBookings WHERE trigger_id=$id) AS reversible
|
||||
FROM CronTriggers WHERE cron_id=$ref AND id=$id`,
|
||||
{ bind, type: QueryTypes.SELECT, transaction });
|
||||
const day = dayjs(receipt.finished_at ?? finishedAt).format('YYYY-MM-DD');
|
||||
await addDailyExit(database, cronId, day, receipt.state, elapsedMs, Boolean(receipt.reversible), transaction);
|
||||
if (receipt.reversible) {
|
||||
await database.query(`UPDATE CronLegacyExitBookings SET stopped=$stopped,
|
||||
stat_id=(SELECT id FROM CrontabStats WHERE ref_id=$ref AND date=$day
|
||||
AND NOT EXISTS (SELECT 1 FROM CronStatRetention WHERE id=1 AND first_day>$day))
|
||||
WHERE trigger_id=$id`, { bind: { ...bind, day, stopped: Number(receipt.state === 'stopped') }, transaction });
|
||||
}
|
||||
}
|
||||
|
||||
export async function addDailyExit(database: Sequelize, cronId: number, day: string, state: string,
|
||||
elapsedMs: number, reversible: boolean, transaction: Transaction) {
|
||||
await database.query(
|
||||
`INSERT INTO "CrontabStats"
|
||||
(ref_id, date, run_count, success_count, fail_count, total_time, max_time, fixed_max_time, createdAt, updatedAt)
|
||||
SELECT $id, $date, 1, $success, $fail, $elapsed, $elapsed, $fixedMax, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP
|
||||
WHERE NOT EXISTS (SELECT 1 FROM CronStatRetention WHERE id=1 AND first_day>$date)
|
||||
ON CONFLICT(ref_id, date) DO UPDATE SET
|
||||
run_count = COALESCE(run_count, 0) + 1,
|
||||
success_count = COALESCE(success_count, 0) + excluded.success_count,
|
||||
fail_count = COALESCE(fail_count, 0) + excluded.fail_count,
|
||||
total_time = COALESCE(total_time, 0) + excluded.total_time,
|
||||
max_time = MAX(COALESCE(max_time, 0), excluded.max_time),
|
||||
fixed_max_time = MAX(COALESCE(fixed_max_time,max_time,0),excluded.fixed_max_time),
|
||||
updatedAt = excluded.updatedAt`,
|
||||
{ transaction, bind: { id: cronId, date: day, fixedMax: reversible ? 0 : elapsedMs,
|
||||
success: Number(state === 'finished'), fail: Number(state === 'failed'), elapsed: elapsedMs } },
|
||||
);
|
||||
}
|
||||
@@ -1,41 +0,0 @@
|
||||
import { EventEmitter } from 'events';
|
||||
import { QueueAddOptions } from 'p-queue-cjs';
|
||||
|
||||
type Job = () => Promise<unknown>;
|
||||
export interface CronQueueOptions extends QueueAddOptions {
|
||||
waitingSignal?: EventEmitter;
|
||||
onRemoved?: () => void;
|
||||
}
|
||||
|
||||
// p-queue checks its signal only after dequeue. Remove expired waits while the
|
||||
// execution slots are still occupied, without aborting a running child.
|
||||
export class CronWaitQueue {
|
||||
private entries: { run: Job; priority: number; detach: () => void }[] = [];
|
||||
|
||||
get size() { return this.entries.length; }
|
||||
|
||||
enqueue(run: Job, options: Partial<CronQueueOptions> = {}) {
|
||||
const { priority = 0, waitingSignal, onRemoved } = options;
|
||||
const remove = () => {
|
||||
const index = this.entries.indexOf(entry);
|
||||
if (index < 0) return;
|
||||
this.entries.splice(index, 1);
|
||||
onRemoved?.();
|
||||
};
|
||||
const entry = { run, priority, detach: () => waitingSignal?.off('expired', remove) };
|
||||
const last = this.entries[this.size - 1];
|
||||
if (!last || last.priority >= priority) this.entries.push(entry);
|
||||
else this.entries.splice(this.entries.findIndex((job) => job.priority < priority), 0, entry);
|
||||
waitingSignal?.once('expired', remove);
|
||||
}
|
||||
|
||||
dequeue() {
|
||||
const next = this.entries.shift();
|
||||
next?.detach();
|
||||
return next?.run;
|
||||
}
|
||||
|
||||
filter(options: Partial<CronQueueOptions>) {
|
||||
return this.entries.filter((entry) => entry.priority === options.priority).map((entry) => entry.run);
|
||||
}
|
||||
}
|
||||
@@ -1,111 +0,0 @@
|
||||
import { promises as fs } from 'fs';
|
||||
import path from 'path';
|
||||
import { resolveFileAccess } from './fileAccess';
|
||||
|
||||
export type DirectoryVersion = [string, string | null];
|
||||
|
||||
function isGone(error: unknown) {
|
||||
const code = (error as NodeJS.ErrnoException).code;
|
||||
return code === 'ENOENT' || code === 'ENOTDIR';
|
||||
}
|
||||
|
||||
async function directoryVersion(root: string, parent: string, blacklist: string[]) {
|
||||
const dir = parent ? resolveFileAccess(root, [parent], blacklist) : root;
|
||||
const denied = () => Object.assign(new Error('Invalid directory'), { status: 403 });
|
||||
if (!dir) throw denied();
|
||||
try {
|
||||
if (await fs.realpath(dir) !== path.join(root, parent)) throw denied();
|
||||
const stat = await fs.lstat(dir, { bigint: true });
|
||||
return stat.isDirectory() ? [stat.dev, stat.ino, stat.mtimeNs, stat.ctimeNs].join(':') : null;
|
||||
} catch (error) {
|
||||
if (isGone(error)) return null;
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
export async function checkDirectoryVersions(root: string, blacklist: string[], versions: DirectoryVersion[]) {
|
||||
const realRoot = await fs.realpath(root);
|
||||
const matches = await Promise.all(versions.map(async ([parent, expected]) => {
|
||||
try {
|
||||
return await directoryVersion(realRoot, parent, blacklist) === expected;
|
||||
} catch (error) {
|
||||
// A formerly accessible directory may now be a symlink outside the root.
|
||||
if ((error as { status?: number }).status === 403) return false;
|
||||
throw error;
|
||||
}
|
||||
}));
|
||||
return matches.every(Boolean);
|
||||
}
|
||||
|
||||
export async function readDirectoryPage(root: string, blacklist: string[], directory: string, after: string,
|
||||
search: string, foldersOnly: boolean, newestFirst: boolean, limit = 50) {
|
||||
const blocked = new Set(blacklist.map(name => name.toLowerCase()));
|
||||
const realRoot = await fs.realpath(root);
|
||||
const versions: DirectoryVersion[] = [];
|
||||
async function entries(parent: string) {
|
||||
const version = await directoryVersion(realRoot, parent, blacklist);
|
||||
versions.push([parent, version]);
|
||||
if (version === null) return [];
|
||||
try {
|
||||
return (await fs.readdir(path.join(realRoot, parent), { withFileTypes: true })).filter(e =>
|
||||
!blocked.has(e.name.toLowerCase()) && (e.isDirectory() || (!foldersOnly && e.isFile())));
|
||||
} catch (error) {
|
||||
if (isGone(error)) return [];
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
const compare = (a: string, b: string) => a < b ? -1 : a > b ? 1 : 0;
|
||||
const rows = [];
|
||||
let next: string | null = null;
|
||||
async function row(parent: string, title: string, directory: boolean) {
|
||||
const key = path.join(parent, title);
|
||||
if (directory) return { title, parent, key, type: 'directory', isLeaf: false };
|
||||
try {
|
||||
const stat = await fs.lstat(path.join(root, key));
|
||||
if (stat.isFile()) return { title, parent, key, type: 'file', isLeaf: true, size: stat.size };
|
||||
} catch (error) { if (!isGone(error)) throw error; }
|
||||
}
|
||||
if (!search) {
|
||||
const sorted = (await entries(directory)).sort((a,b) =>
|
||||
Number(b.isDirectory()) - Number(a.isDirectory()) ||
|
||||
compare(a.name, b.name) * (newestFirst && !a.isDirectory() ? -1 : 1));
|
||||
const selected = sorted.filter(e => {
|
||||
if (!after) return true;
|
||||
const group = e.isDirectory() ? '0' : '1';
|
||||
return group > after[0] || (group === after[0] &&
|
||||
compare(e.name, after.slice(1)) * (newestFirst && !e.isDirectory() ? -1 : 1) > 0);
|
||||
});
|
||||
const page = selected.slice(0, limit);
|
||||
const data = (await Promise.all(page.map(e => row(directory, e.name, e.isDirectory())))).filter(Boolean);
|
||||
if (selected.length > limit) {
|
||||
const last = page[page.length - 1];
|
||||
next = (last.isDirectory() ? '0' : '1') + last.name;
|
||||
}
|
||||
return { data, next, versions };
|
||||
}
|
||||
// Resume a depth-first search at the last visited entry, including on pages with zero matches.
|
||||
async function* walk(parent: string, resume: string[]): AsyncGenerator<{ parent: string; name: string; dir: boolean }> {
|
||||
const items = (await entries(parent)).sort((a,b) => compare(a.name,b.name));
|
||||
for (const item of items) {
|
||||
if (resume.length && item.name < resume[0]) continue;
|
||||
const same = item.name === resume[0];
|
||||
if (!same) yield { parent, name: item.name, dir: item.isDirectory() };
|
||||
if (item.isDirectory()) {
|
||||
try { yield* walk(path.join(parent, item.name), same ? resume.slice(1) : []); }
|
||||
catch (error) {
|
||||
if (!isGone(error) && (error as { status?: number }).status !== 403) throw error;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let visited = 0;
|
||||
for await (const entry of walk('', after ? after.split('/') : [])) {
|
||||
const key = path.join(entry.parent, entry.name);
|
||||
if (key.toLowerCase().includes(search.toLowerCase())) {
|
||||
const item = await row(entry.parent, entry.name, entry.dir);
|
||||
if (item) rows.push(item);
|
||||
}
|
||||
if (++visited >= 512 || rows.length === limit) { next = key; break; }
|
||||
}
|
||||
return { data: rows, next, versions };
|
||||
}
|
||||
@@ -1,34 +0,0 @@
|
||||
import { celebrate, Joi } from 'celebrate';
|
||||
import { Request, Response, NextFunction } from 'express';
|
||||
import { checkDirectoryVersions, readDirectoryPage } from './directoryPage';
|
||||
|
||||
export function directoryCheckHandler(root: () => string, blacklist: string[]) {
|
||||
return [
|
||||
celebrate({ body: Joi.array().items(Joi.array().ordered(
|
||||
Joi.string().allow('').max(4096).required(), Joi.string().max(128).allow(null).required(),
|
||||
).length(2)).min(1).max(128).required() }),
|
||||
async (req: Request, res: Response, next: NextFunction) => {
|
||||
try {
|
||||
const current = await checkDirectoryVersions(root(), blacklist, req.body);
|
||||
res.send({ code: 200, current });
|
||||
} catch (error) { next(error); }
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
export function directoryPageHandler(root: () => string, blacklist: string[], newestFirst: boolean) {
|
||||
return [
|
||||
celebrate({ query: Joi.object({
|
||||
path: Joi.string().allow(''), after: Joi.string().allow(''), search: Joi.string().allow(''),
|
||||
folders: Joi.boolean(), t: Joi.string(),
|
||||
}) }),
|
||||
async (req: Request, res: Response, next: NextFunction) => {
|
||||
try {
|
||||
const { path = '', after = '', search = '', folders } = req.query;
|
||||
const page = await readDirectoryPage(root(), blacklist, String(path), String(after),
|
||||
String(search), String(folders) === 'true', newestFirst);
|
||||
res.send({ code: 200, ...page });
|
||||
} catch (error) { next(error); }
|
||||
},
|
||||
];
|
||||
}
|
||||
@@ -2,10 +2,3 @@
|
||||
export function errStack(error: unknown): string {
|
||||
return error instanceof Error && error.stack ? error.stack : String(error);
|
||||
}
|
||||
|
||||
export class PendingCronInstall extends Error {
|
||||
readonly status = 503;
|
||||
constructor(readonly cronId: number, message: string) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,13 +0,0 @@
|
||||
// The original scheduled CLI wire format maps to its existing persisted trigger ID.
|
||||
export const executionIdPattern = /^(?:client-|legacy-system:\d{1,12}:)[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/;
|
||||
export function executionTriggerId(id: string) {
|
||||
return id.replace('legacy-system:', 'system-cli-').replace(':', '-');
|
||||
}
|
||||
|
||||
// A header lets upgraded clients keep the same identified body on older panels.
|
||||
export function receiptFinishTime(header?: string) {
|
||||
if (header && /^\d{1,13}$/.test(header)) {
|
||||
const time = Number(header);
|
||||
if (time > 0 && time <= Date.now()) return time;
|
||||
}
|
||||
}
|
||||
@@ -24,11 +24,8 @@ export function resolveFileAccess(
|
||||
const resolvedRoot = path.resolve(root);
|
||||
const target = path.resolve(resolvedRoot, ...parts);
|
||||
if (target === resolvedRoot || !isWithin(resolvedRoot, target)) return '';
|
||||
// File systems such as default APFS can resolve a differently cased spelling
|
||||
// of the same entry. Check every protected name without case sensitivity.
|
||||
const blockedNames = new Set(blacklist.map((part) => part.toLowerCase()));
|
||||
const isBlocked = (relative: string) =>
|
||||
relative.split(path.sep).some((part) => blockedNames.has(part.toLowerCase()));
|
||||
relative.split(path.sep).some((part) => blacklist.includes(part));
|
||||
if (isBlocked(path.relative(resolvedRoot, target))) return '';
|
||||
try {
|
||||
const realRoot = fs.realpathSync(resolvedRoot);
|
||||
|
||||
+2
-6
@@ -1,8 +1,8 @@
|
||||
const messages: Record<string, Record<string, string>> = {
|
||||
zh: {},
|
||||
en: {
|
||||
'系统定时规则安装失败,旧规则可能仍在运行,正在重试': 'System crontab installation failed. The previous rules may still run. Retrying.',
|
||||
'Cron表达式格式有误': 'Invalid cron expression',
|
||||
'认证服务暂时不可用,请稍后重试':
|
||||
'Authentication service is temporarily unavailable; try again shortly.',
|
||||
'升级任务启动失败,请检查日志后重试':
|
||||
'Failed to start the update. Check the logs and try again.',
|
||||
'[schedule][停止已运行任务] 任务ID: %s, PID: %s':
|
||||
@@ -25,7 +25,6 @@ const messages: Record<string, Record<string, string>> = {
|
||||
'代理层数不能超过 20': 'Proxy hop count cannot exceed 20',
|
||||
'环境变量 QL_TRUST_PROXY 已生效,系统设置不可覆盖':
|
||||
'QL_TRUST_PROXY is active and cannot be overridden by system settings',
|
||||
环境变量名称不可使用: 'Environment variable name is reserved or invalid',
|
||||
系统配置不存在: 'System configuration does not exist',
|
||||
'历史版本仅支持不超过 1 MiB 的 UTF-8 文本脚本':
|
||||
'Version history only supports UTF-8 text scripts up to 1 MiB',
|
||||
@@ -140,7 +139,6 @@ const messages: Record<string, Record<string, string>> = {
|
||||
验证失败: 'Verification failed',
|
||||
实例不存在或已停止: 'Instance does not exist or stopped',
|
||||
实例已停止: 'Instance stopped',
|
||||
实例已结束: 'Instance already ended',
|
||||
确认停止实例: 'Confirm to stop instance',
|
||||
确认停止运行实例: 'Confirm to stop running instance',
|
||||
确认停止: 'Confirm to stop',
|
||||
@@ -264,8 +262,6 @@ const messages: Record<string, Record<string, string>> = {
|
||||
'执行after命令...': 'Execute after command...',
|
||||
'## 执行结束... %s 耗时 %s 秒':
|
||||
'## Execution finished... %s elapsed %s seconds',
|
||||
'原调度未能恢复,正在重试': 'Could not restore the previous schedule. Retrying.',
|
||||
'任务已修改,请刷新后重试': 'The task has changed. Refresh and try again.',
|
||||
'调度器注册失败,任务创建已回滚':
|
||||
'Scheduler registration failed, task creation rolled back',
|
||||
'调度器注册失败,任务更新已回滚':
|
||||
|
||||
@@ -1,172 +0,0 @@
|
||||
import dayjs from 'dayjs';
|
||||
import { QueryTypes, Sequelize, Transaction } from 'sequelize';
|
||||
|
||||
type DayCounts = {
|
||||
cron_id: number;
|
||||
day: string;
|
||||
successes: number;
|
||||
failures: number;
|
||||
later_successes: number;
|
||||
later_failures: number;
|
||||
has_bookings: number;
|
||||
saved_successes: number;
|
||||
saved_failures: number;
|
||||
};
|
||||
|
||||
// Process one outcome, newest day first. Same-day receipts can only cover
|
||||
// eligible exits. Surplus becomes available to earlier days after this match.
|
||||
function matchDailyCounts(exits: number, saved: number, laterCredits: number, afterLastBooking = 0) {
|
||||
const localMatches = Math.min(saved, exits - afterLastBooking);
|
||||
const deficit = exits - localMatches;
|
||||
const borrowed = Math.min(deficit, laterCredits);
|
||||
return { missing: deficit - borrowed, remaining: laterCredits - borrowed + saved - localMatches };
|
||||
}
|
||||
|
||||
// A legacy terminal status needs a matching exit code. An identified supervisor
|
||||
// also knows a child failed when the OS returns a signal instead of a code.
|
||||
const confirmedResult = `t.started_at IS NOT NULL AND t.finished_at>=t.started_at
|
||||
AND t.state IN ('finished','failed')
|
||||
AND (t.source<>'legacy' OR (
|
||||
((t.state='finished' AND t.exit_code=0) OR (t.state='failed' AND t.exit_code<>0))
|
||||
AND NOT EXISTS (SELECT 1 FROM RunningInstances sibling
|
||||
LEFT JOIN CronTriggers linked ON linked.instance_id=sibling.id
|
||||
WHERE sibling.cron_id=i.cron_id AND sibling.pid=i.pid AND sibling.finished_at=i.finished_at
|
||||
AND sibling.id<>i.id AND sibling.status IN (1,3)
|
||||
AND (linked.id IS NULL OR (linked.source='legacy' AND linked.owner IS NULL))
|
||||
AND (sibling.started_at<>i.started_at OR COALESCE(sibling.log_path,'')<>COALESCE(i.log_path,'')
|
||||
OR sibling.status<>i.status OR sibling.exit_code IS NOT i.exit_code OR linked.id IS NOT NULL))))`;
|
||||
|
||||
export function readDailyResults(database: Sequelize, cronId: number) {
|
||||
const today = dayjs().startOf('day');
|
||||
const first = today.subtract(6, 'day');
|
||||
const next = today.add(1, 'day');
|
||||
return database.query<{
|
||||
day: string; exitSuccess: number; exitFail: number;
|
||||
bookedSuccess: number; bookedFail: number; supplement: number;
|
||||
}>(`WITH results AS (
|
||||
SELECT date(t.finished_at/1000,'unixepoch','localtime') AS day,
|
||||
SUM(t.state='finished') AS exitSuccess,SUM(t.state='failed') AS exitFail,
|
||||
0 AS bookedSuccess,0 AS bookedFail,0 AS supplement
|
||||
FROM CronTriggers t LEFT JOIN RunningInstances i ON i.id=t.instance_id
|
||||
WHERE t.cron_id=$id AND t.finished_at >= $start AND t.finished_at < $end
|
||||
AND t.reason IS NOT 'spawn' AND ${confirmedResult} GROUP BY day
|
||||
UNION ALL
|
||||
SELECT date,0,0,COALESCE(success_count,0),COALESCE(fail_count,0),untimed_count
|
||||
FROM CrontabStats WHERE ref_id=$id AND date >= $first AND date < $next
|
||||
) SELECT day,SUM(exitSuccess) AS exitSuccess,SUM(exitFail) AS exitFail,
|
||||
SUM(bookedSuccess) AS bookedSuccess,SUM(bookedFail) AS bookedFail,SUM(supplement) AS supplement
|
||||
FROM results GROUP BY day ORDER BY day DESC`, { type: QueryTypes.SELECT, bind: {
|
||||
id: cronId, start: first.valueOf(), end: next.valueOf(),
|
||||
first: first.format('YYYY-MM-DD'), next: next.format('YYYY-MM-DD'),
|
||||
} });
|
||||
}
|
||||
|
||||
// Run under the schema migration's write lock, before accepting new receipts.
|
||||
export async function repairLegacyDailyStatistics(database: Sequelize, transaction: Transaction, priorVersion: 0 | 1 | 2) {
|
||||
// Old panels updated every outstanding start with the reported PID. Identical
|
||||
// copies of a start prove only one exit; conflicting rows cannot identify it.
|
||||
const imported = await database.query(`WITH exits AS (
|
||||
SELECT MIN(i.id) AS instance FROM RunningInstances i
|
||||
JOIN Crontabs c ON c.id=i.cron_id
|
||||
LEFT JOIN CronTriggers linked ON linked.instance_id=i.id
|
||||
WHERE (linked.id IS NULL OR (linked.source='legacy' AND linked.owner IS NULL))
|
||||
AND i.status IN (1,3) AND i.pid>0 AND i.started_at>0 AND i.finished_at>=i.started_at
|
||||
AND i.finished_at*1000>=COALESCE((SELECT cutoff FROM CronHistoryRetention WHERE id=1),0)
|
||||
GROUP BY i.cron_id,i.pid,i.finished_at
|
||||
HAVING MIN(i.started_at)=MAX(i.started_at)
|
||||
AND COUNT(DISTINCT COALESCE(i.log_path,''))=1 AND MIN(i.status)=MAX(i.status)
|
||||
AND COUNT(i.exit_code)=COUNT(*) AND MIN(i.exit_code)=MAX(i.exit_code)
|
||||
AND COUNT(linked.id)=0
|
||||
)
|
||||
INSERT INTO CronTriggers(id,cron_id,source,state,observed_at,started_at,finished_at,instance_id,log_path,exit_code,counted)
|
||||
SELECT 'legacy-db-' || i.id,i.cron_id,'legacy',CASE i.status WHEN 1 THEN 'finished' ELSE 'failed' END,
|
||||
i.started_at*1000,i.started_at*1000,i.finished_at*1000,i.id,i.log_path,i.exit_code,1
|
||||
FROM exits JOIN RunningInstances i ON i.id=exits.instance
|
||||
WHERE (i.status=1 AND i.exit_code=0) OR (i.status=3 AND i.exit_code<>0)`,
|
||||
{ transaction, type: QueryTypes.BULKUPDATE });
|
||||
|
||||
// A newly imported last run must have the same owner it would acquire through
|
||||
// the normal handoff. An older exit must never replace a more recent start.
|
||||
if (imported) await database.query(`WITH ranked AS (
|
||||
SELECT cron_id,instance_id,started_at/1000 AS start,(finished_at-started_at)/1000 AS elapsed,
|
||||
ROW_NUMBER() OVER (PARTITION BY cron_id ORDER BY started_at DESC,instance_id DESC) AS position
|
||||
FROM CronTriggers WHERE source='legacy' AND id LIKE 'legacy-db-%'
|
||||
)
|
||||
UPDATE Crontabs AS c SET (last_instance_id,last_execution_time,last_running_time)=
|
||||
(SELECT instance_id,start,elapsed FROM ranked WHERE cron_id=c.id AND position=1)
|
||||
WHERE EXISTS (SELECT 1 FROM ranked r WHERE r.cron_id=c.id AND r.position=1 AND
|
||||
(c.last_execution_time IS NULL OR c.last_execution_time<r.start OR
|
||||
(c.last_execution_time=r.start AND (c.last_instance_id IS NULL OR c.last_instance_id<r.instance_id)))
|
||||
AND NOT EXISTS (SELECT 1 FROM RunningInstances i WHERE i.cron_id=c.id AND
|
||||
(i.started_at>r.start OR (i.started_at=r.start AND i.id>r.instance_id))))`,
|
||||
{ transaction });
|
||||
|
||||
// Statistics retention removes whole dates across tasks. When the old panel
|
||||
// retained no earlier totals, yesterday is the oldest date even a 1-day policy keeps.
|
||||
const yesterday = dayjs().subtract(1,'day').format('YYYY-MM-DD');
|
||||
const days = await database.query<DayCounts>(`WITH exits AS (
|
||||
SELECT t.cron_id,t.state,date(t.finished_at/1000,'unixepoch','localtime') AS day,
|
||||
t.started_at,i.createdAt,t.id
|
||||
FROM CronTriggers t LEFT JOIN RunningInstances i ON i.id=t.instance_id
|
||||
WHERE t.counted=1 AND ${confirmedResult}
|
||||
), ordered AS (
|
||||
SELECT e.*, CASE WHEN e.id LIKE 'legacy-db-%' AND s.untimed_count=0
|
||||
AND date(s.updatedAt,'localtime')=e.day AND julianday(s.createdAt)<=julianday(s.updatedAt)
|
||||
AND e.started_at/1000>CAST(strftime('%s',s.updatedAt) AS INTEGER)
|
||||
AND julianday(e.createdAt)>julianday(s.updatedAt) THEN 1 ELSE 0 END AS later
|
||||
FROM exits e LEFT JOIN CrontabStats s ON s.ref_id=e.cron_id AND s.date=e.day
|
||||
), evidence AS (
|
||||
SELECT cron_id,day,SUM(state='finished') AS successes,SUM(state='failed') AS failures,
|
||||
SUM(later*(state='finished')) AS later_successes,SUM(later*(state='failed')) AS later_failures,
|
||||
0 AS has_bookings,0 AS saved_successes,0 AS saved_failures FROM ordered GROUP BY cron_id,day
|
||||
UNION ALL
|
||||
SELECT ref_id,date,0,0,0,0,1,COALESCE(success_count,0),COALESCE(fail_count,0) FROM CrontabStats
|
||||
)
|
||||
SELECT cron_id,day,MAX(has_bookings) AS has_bookings,SUM(successes) AS successes,SUM(failures) AS failures,
|
||||
SUM(later_successes) AS later_successes,SUM(later_failures) AS later_failures,
|
||||
SUM(saved_successes) AS saved_successes,SUM(saved_failures) AS saved_failures
|
||||
FROM evidence WHERE day>=MIN($yesterday,COALESCE((SELECT MIN(date) FROM CrontabStats),$yesterday))
|
||||
AND day>=COALESCE((SELECT first_day FROM CronStatRetention WHERE id=1),'')
|
||||
GROUP BY cron_id,day ORDER BY cron_id,day DESC`, { type: QueryTypes.SELECT, transaction, bind:{ yesterday } });
|
||||
|
||||
// Anonymous receipts cannot identify a particular exit. Match nearest
|
||||
// eligible days first; never move already booked counts or elapsed samples.
|
||||
let task: number | undefined;
|
||||
let successCredit = 0, failureCredit = 0;
|
||||
let priorSuccessCredit = 0, priorFailureCredit = 0;
|
||||
for (const day of days) {
|
||||
if (day.cron_id !== task) {
|
||||
task = day.cron_id;
|
||||
successCredit = failureCredit = priorSuccessCredit = priorFailureCredit = 0;
|
||||
}
|
||||
const successes = matchDailyCounts(day.successes, day.saved_successes, successCredit, day.later_successes);
|
||||
const failures = matchDailyCounts(day.failures, day.saved_failures, failureCredit, day.later_failures);
|
||||
successCredit = successes.remaining;
|
||||
failureCredit = failures.remaining;
|
||||
let success = successes.missing, failure = failures.missing;
|
||||
if (priorVersion === 2) {
|
||||
// Replaying v2 on the current snapshot could resurrect a cleaned-up day.
|
||||
// Only the extra lower bound established by v3 is new evidence.
|
||||
const priorSuccess = matchDailyCounts(day.successes, day.saved_successes, priorSuccessCredit);
|
||||
const priorFailure = matchDailyCounts(day.failures, day.saved_failures, priorFailureCredit);
|
||||
priorSuccessCredit = priorSuccess.remaining;
|
||||
priorFailureCredit = priorFailure.remaining;
|
||||
success = Math.max(0, success - priorSuccess.missing);
|
||||
failure = Math.max(0, failure - priorFailure.missing);
|
||||
}
|
||||
// Old repairs did not journal deletions. An absent task/day could have
|
||||
// been cleared after a supplement. Preserve the gap on repeat upgrades.
|
||||
if (priorVersion && !day.has_bookings) continue;
|
||||
if (!success && !failure) continue;
|
||||
// Anonymous elapsed samples have no execution identity. Preserve measured
|
||||
// times; adding instance wall times here could count the same sample twice.
|
||||
await database.query(`INSERT INTO CrontabStats
|
||||
(ref_id,date,run_count,success_count,fail_count,untimed_count,total_time,max_time,createdAt,updatedAt)
|
||||
VALUES ($task,$day,$runs,$success,$failure,$runs,0,0,CURRENT_TIMESTAMP,CURRENT_TIMESTAMP)
|
||||
ON CONFLICT(ref_id,date) DO UPDATE SET run_count=COALESCE(run_count,0)+excluded.run_count,
|
||||
success_count=COALESCE(success_count,0)+excluded.success_count,
|
||||
fail_count=COALESCE(fail_count,0)+excluded.fail_count,
|
||||
untimed_count=untimed_count+excluded.untimed_count,updatedAt=CURRENT_TIMESTAMP`,
|
||||
{ transaction, bind: { task,day:day.day,runs:success+failure,success,failure } });
|
||||
}
|
||||
}
|
||||
+15
-55
@@ -1,18 +1,12 @@
|
||||
import fs from 'fs/promises';
|
||||
import { createHash } from 'crypto';
|
||||
|
||||
export const DEFAULT_LOG_CHUNK_BYTES = 256 * 1024;
|
||||
export const MAX_LOG_CHUNK_BYTES = 1024 * 1024;
|
||||
|
||||
// The viewer retains at most one Mi UTF-16 code units.
|
||||
const CURSOR_WINDOW_BYTES = 4 * MAX_LOG_CHUNK_BYTES;
|
||||
|
||||
export interface LogReadOptions {
|
||||
offset?: number;
|
||||
limit?: number;
|
||||
tail?: boolean;
|
||||
follow?: boolean;
|
||||
cursor?: string;
|
||||
}
|
||||
|
||||
export interface LogChunk {
|
||||
@@ -21,8 +15,6 @@ export interface LogChunk {
|
||||
nextOffset: number;
|
||||
total: number;
|
||||
truncated: boolean;
|
||||
cursor?: string;
|
||||
reset?: boolean;
|
||||
}
|
||||
|
||||
function normalizeLimit(limit?: number) {
|
||||
@@ -57,10 +49,6 @@ function completeUtf8End(buffer: Buffer, start: number, end: number) {
|
||||
return end - sequenceStart < expectedLength ? sequenceStart : end;
|
||||
}
|
||||
|
||||
function logDigest(identity: string, from: number, bytes: Buffer) {
|
||||
return createHash('sha256').update(`${identity}:${from}:`).update(bytes).digest('hex');
|
||||
}
|
||||
|
||||
export async function readLogChunk(
|
||||
filePath: string,
|
||||
options: LogReadOptions = {},
|
||||
@@ -68,43 +56,23 @@ export async function readLogChunk(
|
||||
let handle: fs.FileHandle | undefined;
|
||||
try {
|
||||
handle = await fs.open(filePath, 'r');
|
||||
const stat = await handle.stat({ bigint: true });
|
||||
const total = Number(stat.size);
|
||||
const identity = `${stat.dev}:${stat.ino}`;
|
||||
const { size: total } = await handle.stat();
|
||||
const limit = normalizeLimit(options.limit);
|
||||
const requestedOffset = Number.isFinite(options.offset)
|
||||
? Math.max(0, Math.trunc(options.offset!))
|
||||
? Math.trunc(options.offset!)
|
||||
: undefined;
|
||||
let start = options.tail || requestedOffset === undefined
|
||||
const requestedStart =
|
||||
options.tail || requestedOffset === undefined
|
||||
? Math.max(total - limit, 0)
|
||||
: Math.min(requestedOffset, total);
|
||||
const resume = options.cursor && !options.tail && requestedOffset !== undefined;
|
||||
const [fromText, digest] = resume ? options.cursor!.split('.') : [];
|
||||
let from = resume ? Number(fromText) : start;
|
||||
let reset = Boolean(resume && (
|
||||
requestedOffset !== start || !Number.isSafeInteger(from) ||
|
||||
from < 0 || from > start || start - from > CURSOR_WINDOW_BYTES
|
||||
));
|
||||
if (reset) from = start = 0;
|
||||
|
||||
// Read the previously displayed bytes and their continuation together.
|
||||
// A truncate followed by regrowth can leave both size and inode unchanged.
|
||||
const readWindow = async (position: number, end: number) => {
|
||||
const data = Buffer.allocUnsafe(Math.min(end, total) - position);
|
||||
const { bytesRead } = await handle!.read(data, 0, data.length, position);
|
||||
return data.subarray(0, bytesRead);
|
||||
};
|
||||
let window = await readWindow(from, start + limit + 3);
|
||||
if (resume && !reset) {
|
||||
const prefix = window.subarray(0, start - from);
|
||||
if (prefix.length !== start - from || logDigest(identity, from, prefix) !== digest) {
|
||||
reset = true;
|
||||
start = from = 0;
|
||||
window = await readWindow(0, limit + 3);
|
||||
}
|
||||
}
|
||||
const buffer = window.subarray(start - from);
|
||||
const bytesRead = buffer.length;
|
||||
: Math.min(Math.max(requestedOffset, 0), total);
|
||||
const length = Math.min(limit + 3, total - requestedStart);
|
||||
const buffer = Buffer.allocUnsafe(length);
|
||||
const { bytesRead } = await handle.read(
|
||||
buffer,
|
||||
0,
|
||||
length,
|
||||
requestedStart,
|
||||
);
|
||||
let leadingBytes = 0;
|
||||
while (
|
||||
leadingBytes < bytesRead &&
|
||||
@@ -112,20 +80,12 @@ export async function readLogChunk(
|
||||
) {
|
||||
leadingBytes++;
|
||||
}
|
||||
const offset = start + leadingBytes;
|
||||
const offset = requestedStart + leadingBytes;
|
||||
const candidateEnd = Math.min(leadingBytes + limit, bytesRead);
|
||||
const contentEnd = completeUtf8End(buffer, leadingBytes, candidateEnd);
|
||||
const nextOffset = start + contentEnd;
|
||||
|
||||
let cursor: string | undefined;
|
||||
if (options.follow || options.cursor) {
|
||||
const retainedFrom = Math.max(from, nextOffset - CURSOR_WINDOW_BYTES);
|
||||
cursor = resume && !reset && nextOffset === start ? options.cursor :
|
||||
`${retainedFrom}.${logDigest(identity, retainedFrom, window.subarray(retainedFrom - from, nextOffset - from))}`;
|
||||
}
|
||||
const nextOffset = requestedStart + contentEnd;
|
||||
|
||||
return {
|
||||
...(cursor && { cursor, reset }),
|
||||
content: buffer.subarray(leadingBytes, contentEnd).toString('utf8'),
|
||||
offset,
|
||||
nextOffset,
|
||||
|
||||
@@ -1,390 +0,0 @@
|
||||
// Keep the command's actual exit available until its SQLite transaction commits.
|
||||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
const { createHash, randomUUID } = require('node:crypto');
|
||||
|
||||
const idPattern = /^[a-z0-9-]{1,120}$/;
|
||||
|
||||
// A full data volume can still have room for a directory entry. In this format
|
||||
// the empty file publishes the tuple atomically, including its execution-bound
|
||||
// checksum. Keep the encoded name when moving it into a collector-private slot.
|
||||
const metadataName = /^\.pending\.([a-z0-9-]{1,120})\.full-(\d{1,3}|SIG[A-Z0-9]+)-(\d{1,16})-([0-9a-f]{64})-([a-zA-Z0-9_]+)$/;
|
||||
|
||||
// The digest only guards disposal of legacy bytes. It cannot establish an exit.
|
||||
const legacyCapture = /^\.pending\.([a-z0-9-]{1,120})\.l-([0-9a-f]{32})-[0-9a-f]{24}$/;
|
||||
const claimName = /^\.claim(-bound)?\.([a-z0-9-]{1,120})\.[a-zA-Z0-9]{6}$/;
|
||||
|
||||
function metadataReceipt(file) {
|
||||
const name = path.basename(file);
|
||||
return metadataName.exec(name === '.pending.claimed' ? path.basename(path.dirname(file)) : name);
|
||||
}
|
||||
|
||||
function storageFull(error) {
|
||||
const codes = [error?.code, error?.original?.code, error?.parent?.code];
|
||||
if (codes.some(code => ['ENOSPC', 'EDQUOT', 'SQLITE_FULL'].includes(code))) return true;
|
||||
const directory = receiptDirectory();
|
||||
if (directory && codes.includes('SQLITE_CANTOPEN')) {
|
||||
// SQLite maps a failed journal creation to CANTOPEN even when the kernel
|
||||
// reported ENOSPC. Other open failures keep their normal error semantics.
|
||||
try {
|
||||
const capacity = fs.statfsSync(path.dirname(directory));
|
||||
return capacity.bavail === 0 || (capacity.files > 0 && capacity.ffree === 0);
|
||||
} catch { return false; }
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
function receiptDirectory() {
|
||||
const data = process.env.QL_DATA_DIR || (process.env.QL_DIR && path.join(process.env.QL_DIR, 'data'));
|
||||
if (data) return path.join(data, 'db', 'cron-exits');
|
||||
}
|
||||
|
||||
function receiptPath(id) {
|
||||
const directory = receiptDirectory();
|
||||
if (directory && typeof id === 'string' && idPattern.test(id)) return path.join(directory, id);
|
||||
}
|
||||
|
||||
async function listReceiptFiles(directory, prefix) {
|
||||
if (!directory) return [];
|
||||
try {
|
||||
const entries = await fs.promises.readdir(directory, { withFileTypes: true });
|
||||
const files = [];
|
||||
for (const entry of entries) {
|
||||
if (!entry.isFile() || !entry.name.startsWith(prefix)) continue;
|
||||
const id = entry.name.slice(prefix.length);
|
||||
if (idPattern.test(id)) files.push({ id, file: path.join(directory, entry.name) });
|
||||
}
|
||||
return files;
|
||||
} catch (error) {
|
||||
if (error.code === 'ENOENT') return [];
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
async function publishedExits() {
|
||||
return (await listReceiptFiles(receiptDirectory(), '')).map(entry => entry.id);
|
||||
}
|
||||
|
||||
// flock attaches to the open file description. The child inherits fd 3 and
|
||||
// exits immediately. Closing the panel's handle (including on SIGKILL)
|
||||
// releases the lock without leaving a lock file on a full volume.
|
||||
async function lockClaim(handle, shared) {
|
||||
const run = (program, args) => new Promise((resolve, reject) => {
|
||||
const child = require('node:child_process').spawn(program, args, {
|
||||
stdio: ['ignore', 'ignore', 'ignore', handle.fd],
|
||||
});
|
||||
child.once('error', reject);
|
||||
child.once('exit', (code, signal) => {
|
||||
if (code === 0 || code === 1) resolve(code === 0);
|
||||
else reject(new Error(`Receipt directory lock failed (${signal || code})`));
|
||||
});
|
||||
});
|
||||
try {
|
||||
return await run('flock', ['-n', shared ? '-s' : '-x', '3']);
|
||||
} catch (error) {
|
||||
if (error.code !== 'ENOENT') throw error;
|
||||
// Python is also shipped with the task supervisor on minimal Linux images.
|
||||
const program = 'import fcntl,sys\ntry: fcntl.flock(3, fcntl.LOCK_NB | fcntl.LOCK_' +
|
||||
(shared ? 'SH' : 'EX') + ')\nexcept BlockingIOError: sys.exit(1)';
|
||||
return run('python3', ['-c', program]);
|
||||
}
|
||||
}
|
||||
|
||||
// Move the current directory entry to a fresh, recoverable name outside the
|
||||
// reusable claim directory. A writer can replace that entry without flock.
|
||||
// Only the bytes actually captured by this attempt authorize its final unlink.
|
||||
/** @param {string} id @param {string} file @param {{outcome: string, time: number}} [booked] */
|
||||
async function retireLegacyFile(id, file, booked) {
|
||||
const directory = receiptDirectory();
|
||||
const sourceDir = path.dirname(file);
|
||||
const slot = path.basename(file);
|
||||
const bound = /^\.(pending|published)\./.test(slot) && !legacyCapture.test(slot);
|
||||
const metadata = metadataReceipt(file);
|
||||
const parent = claimName.exec(path.basename(sourceDir));
|
||||
const privateSlot = path.dirname(sourceDir) === directory &&
|
||||
(parent?.[2] === id && slot === (parent[1] ? '.pending.claimed' : 'receipt') ||
|
||||
metadata?.[1] === id && slot === '.pending.claimed');
|
||||
if (!directory || !idPattern.test(id)) return;
|
||||
const dbDir = path.dirname(directory);
|
||||
const localBin = path.join(directory, '.reclaim');
|
||||
const fromBin = sourceDir === dbDir || sourceDir === localBin;
|
||||
if (sourceDir !== directory && !privateSlot && !(fromBin && captureId(slot) === id)) return;
|
||||
|
||||
const matches = exit => exit && !exit.namedExit && (exit.version === 1
|
||||
? booked && exit.time === booked.time && (exit.signal ?? String(exit.code)) === booked.outcome
|
||||
: !bound);
|
||||
let handle, binHandle;
|
||||
try {
|
||||
if ((privateSlot || sourceDir === localBin) && process.platform === 'linux') {
|
||||
handle = await fs.promises.open(sourceDir, fs.constants.O_DIRECTORY | fs.constants.O_NOFOLLOW);
|
||||
if (privateSlot && !await lockClaim(handle, true)) return;
|
||||
}
|
||||
const source = handle ? `/proc/self/fd/${handle.fd}/${slot}` : file;
|
||||
// A canonical publication may only be readable after the move. For a
|
||||
// recovered copy, first avoid moving an unsettled witness on every scan.
|
||||
const previous = await readExit(id, source, file);
|
||||
if (slot !== id && !matches(previous)) return;
|
||||
const nonce = randomUUID();
|
||||
let name;
|
||||
if (metadata) {
|
||||
name = metadata[0].slice(0, -metadata[5].length) + 'r_' + nonce.replace(/-/g, '').slice(0, 16);
|
||||
} else if (bound || !previous || previous.version === 1) {
|
||||
name = `.pending.${id}.r-${nonce}`;
|
||||
} else {
|
||||
const digest = exitChecksum(id, previous.code, previous.signal, previous.time).slice(0, 32);
|
||||
name = `.pending.${id}.l-${digest}-${nonce.replace(/-/g, '').slice(0, 24)}`;
|
||||
}
|
||||
// The database directory is outside the writers' receipt namespace and
|
||||
// already exists even at zero free inodes. A separately mounted journal
|
||||
// requires a disposal directory on its own filesystem.
|
||||
let bin = sourceDir === localBin ? localBin : dbDir;
|
||||
const pinBin = async () => {
|
||||
binHandle = await fs.promises.open(localBin, fs.constants.O_DIRECTORY | fs.constants.O_NOFOLLOW);
|
||||
return process.platform === 'linux' ? `/proc/self/fd/${binHandle.fd}/${name}` : path.join(localBin, name);
|
||||
};
|
||||
let captured = path.join(bin, name);
|
||||
if (bin === localBin) captured = handle ? path.join(path.dirname(source), name) : await pinBin();
|
||||
try {
|
||||
await fs.promises.rename(source, captured);
|
||||
} catch (error) {
|
||||
if (error.code !== 'EXDEV' || bin === localBin) throw error;
|
||||
await fs.promises.mkdir(localBin, { mode: 0o700, recursive: true });
|
||||
bin = localBin;
|
||||
captured = await pinBin();
|
||||
await fs.promises.rename(source, captured);
|
||||
}
|
||||
const actual = await readExit(id, captured, path.join(bin, name));
|
||||
// An unreadable source offers no authority to discard unbound bytes.
|
||||
const sameExit = previous && actual && actual.version === previous.version &&
|
||||
actual.code === previous.code && actual.signal === previous.signal && actual.time === previous.time;
|
||||
if (matches(actual) && (sameExit || (!previous && actual.version === 1))) {
|
||||
await fs.promises.unlink(captured);
|
||||
} else if (actual !== undefined) {
|
||||
// A differing, torn or unreadable file is evidence for another pass.
|
||||
// Persist its new directory entry before releasing the original directory.
|
||||
if (binHandle) await binHandle.sync();
|
||||
else if (bin !== sourceDir || !handle) syncDirectory(bin);
|
||||
if (bin === localBin) syncDirectory(directory);
|
||||
if (handle) await handle.sync();
|
||||
else if (sourceDir !== bin) syncDirectory(sourceDir);
|
||||
}
|
||||
} catch (error) {
|
||||
if (error.code !== 'ENOENT') throw error;
|
||||
} finally {
|
||||
if (binHandle) await binHandle.close();
|
||||
if (handle) await handle.close();
|
||||
if (privateSlot) await fs.promises.rmdir(sourceDir).catch(() => {});
|
||||
}
|
||||
}
|
||||
|
||||
function captureId(name) {
|
||||
const marker = metadataName.exec(name);
|
||||
if (marker && /^r_[0-9a-f]{16}$/.test(marker[5])) return marker[1];
|
||||
const match = legacyCapture.exec(name) ??
|
||||
/^\.pending\.([a-z0-9-]{1,120})\.r-[0-9a-f-]{36}$/.exec(name);
|
||||
return match?.[1];
|
||||
}
|
||||
|
||||
async function receiptEntries(directory) {
|
||||
try { return await fs.promises.readdir(directory, { withFileTypes: true }); }
|
||||
catch (error) { if (error.code === 'ENOENT') return []; throw error; }
|
||||
}
|
||||
|
||||
async function retiringExits() {
|
||||
const dir = receiptDirectory();
|
||||
if (!dir) return [];
|
||||
const files = [];
|
||||
const bins = [path.dirname(dir)];
|
||||
for (const entry of await receiptEntries(dir)) {
|
||||
if (entry.isDirectory() && entry.name === '.reclaim') {
|
||||
bins.push(path.join(dir, entry.name));
|
||||
continue;
|
||||
}
|
||||
const claim = claimName.exec(entry.name);
|
||||
const metadata = metadataName.exec(entry.name);
|
||||
if ((claim || metadata) && entry.isDirectory()) {
|
||||
const directory = path.join(dir, entry.name);
|
||||
try { await fs.promises.rmdir(directory); continue; } catch (error) {
|
||||
if (error.code === 'ENOENT') continue;
|
||||
}
|
||||
files.push({ id: metadata ? metadata[1] : claim[2], file: path.join(directory, metadata || claim[1] ? '.pending.claimed' : 'receipt') });
|
||||
continue;
|
||||
}
|
||||
const match = metadata ?? /^\.(?:retiring|collecting)\.([a-z0-9-]{1,120})\.[0-9a-f-]{36}$/.exec(entry.name)
|
||||
?? /^\.pending\.([a-z0-9-]{1,120})\.[a-z0-9_-]{1,64}$/.exec(entry.name)
|
||||
?? /^\.published\.([a-z0-9-]{1,120})\.[0-9a-f]{64}$/.exec(entry.name);
|
||||
if (entry.isFile() && match) files.push({ id:match[1], file:path.join(dir,entry.name) });
|
||||
}
|
||||
for (const bin of bins) {
|
||||
for (const entry of await receiptEntries(bin)) {
|
||||
const id = entry.isFile() && captureId(entry.name);
|
||||
if (id) files.push({ id, file:path.join(bin,entry.name) });
|
||||
}
|
||||
}
|
||||
return files;
|
||||
}
|
||||
|
||||
async function publishedScriptStarts() {
|
||||
const directory = process.env.QL_DIR && path.join(process.env.QL_DIR, '.tmp');
|
||||
try {
|
||||
return await listReceiptFiles(directory, 'cron-start-');
|
||||
} catch {
|
||||
// Optional entry instrumentation must not prevent exit recovery.
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
function validExit(code, signal, time) {
|
||||
return Number.isSafeInteger(time) && time > 0 && Number.isFinite(new Date(time).getTime()) &&
|
||||
((Number.isInteger(code) && code >= 0 && code <= 255 && signal === null) ||
|
||||
(code === null && typeof signal === 'string' && /^SIG[A-Z0-9]+$/.test(signal)));
|
||||
}
|
||||
|
||||
// The Python supervisor uses the same compact JSON array of ASCII values.
|
||||
function exitChecksum(id, code, signal, time) {
|
||||
return createHash('sha256').update(JSON.stringify([id, code, signal, time])).digest('hex');
|
||||
}
|
||||
|
||||
function syncDirectory(directory) {
|
||||
const fd = fs.openSync(directory, fs.constants.O_RDONLY | fs.constants.O_DIRECTORY);
|
||||
try { fs.fsyncSync(fd); } finally { fs.closeSync(fd); }
|
||||
}
|
||||
|
||||
function writeExit(id, code, signal, time) {
|
||||
if (!validExit(code, signal, time)) throw new TypeError('Invalid command exit receipt');
|
||||
const file = receiptPath(id);
|
||||
if (!file) return;
|
||||
fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
|
||||
const checksum = exitChecksum(id, code, signal, time);
|
||||
const receipt = JSON.stringify({ code, signal, time, version: 1, checksum });
|
||||
// Creation is the first durable observation. No data block is needed for
|
||||
// this witness. Keep the regular JSON publication for earlier readers.
|
||||
const directory = path.dirname(file);
|
||||
const prefix = '.pending.' + id + '.';
|
||||
const marker = prefix + 'full-' + (signal ?? code) + '-' + time + '-' + checksum + '-';
|
||||
const publish = (name, content) => {
|
||||
for (;;) {
|
||||
const target = path.join(directory, name + randomUUID().replace(/-/g, '').slice(0, 16));
|
||||
try {
|
||||
fs.writeFileSync(target, content, { flag: 'wx', mode: 0o600, flush: Boolean(content) });
|
||||
return target;
|
||||
} catch (error) {
|
||||
if (error.code !== 'EEXIST') throw error;
|
||||
}
|
||||
}
|
||||
};
|
||||
publish(marker, '');
|
||||
// ext4 journals the empty inode and directory entry together. Also fence the
|
||||
// directory's own entry: another publisher may just have created it.
|
||||
syncDirectory(directory);
|
||||
syncDirectory(path.dirname(directory));
|
||||
try {
|
||||
if (fs.statfsSync(directory).bavail === 0) return;
|
||||
const source = publish(marker, receipt);
|
||||
try { fs.linkSync(source, file); }
|
||||
catch (error) {
|
||||
if (error.code === 'ENOENT') return;
|
||||
if (error.code !== 'EEXIST') throw error;
|
||||
// A panel from before metadata receipts can still discover this retry.
|
||||
for (;;) {
|
||||
try { fs.linkSync(source, path.join(directory, prefix + randomUUID())); break; }
|
||||
catch (linkError) {
|
||||
if (linkError.code === 'ENOENT') break;
|
||||
if (linkError.code !== 'EEXIST') throw linkError;
|
||||
}
|
||||
}
|
||||
}
|
||||
// Older panels find the JSON only through this newly created link.
|
||||
syncDirectory(directory);
|
||||
} catch (error) {
|
||||
if (!storageFull(error)) throw error;
|
||||
}
|
||||
}
|
||||
|
||||
function parseExit(id, value) {
|
||||
if (!value || !validExit(value.code, value.signal, value.time)) return null;
|
||||
const { code, signal, time, checksum, version } = value;
|
||||
if (version !== undefined || checksum !== undefined) {
|
||||
if (version !== 1 || checksum !== exitChecksum(id, code, signal, time)) return null;
|
||||
} else if (Object.keys(value).length !== 3) {
|
||||
return null;
|
||||
}
|
||||
return { code, signal, time, version };
|
||||
}
|
||||
|
||||
// undefined means no publication. null means a result cannot yet be trusted.
|
||||
async function readExit(id, file = receiptPath(id), publication = file) {
|
||||
if (!file) return;
|
||||
try {
|
||||
const handle = await fs.promises.open(file, fs.constants.O_RDONLY | fs.constants.O_NONBLOCK | fs.constants.O_NOFOLLOW);
|
||||
try {
|
||||
// Bound CPU and memory even if the damaged file is growing.
|
||||
const buffer = Buffer.alloc(1025);
|
||||
let size = 0;
|
||||
while (size < buffer.length) {
|
||||
const { bytesRead } = await handle.read(buffer, size, buffer.length - size, null);
|
||||
if (!bytesRead) break;
|
||||
size += bytesRead;
|
||||
}
|
||||
if (size === buffer.length) return null;
|
||||
const metadata = metadataReceipt(publication);
|
||||
const bytes = buffer.toString('utf8', 0, size);
|
||||
let namedExit;
|
||||
if (metadata && metadata[1] === id && (await handle.stat()).isFile()) {
|
||||
const [, , outcome, end, checksum] = metadata;
|
||||
const signal = outcome.startsWith('SIG') ? outcome : null;
|
||||
const value = { code: signal ? null : Number(outcome), signal, time: Number(end), version: 1, checksum };
|
||||
// Both current publishers serialize in this order. Accept a torn body
|
||||
// only when every byte matches the tuple independently published by
|
||||
// the filename. Validate replacement files on their own bytes below.
|
||||
namedExit = parseExit(id, value);
|
||||
const json = JSON.stringify(value);
|
||||
if (json.startsWith(bytes)) {
|
||||
return namedExit && { ...namedExit, file, namedExit: undefined };
|
||||
}
|
||||
}
|
||||
const exit = parseExit(id, JSON.parse(bytes));
|
||||
const guard = legacyCapture.exec(path.basename(publication));
|
||||
if (guard && exit && exit.version !== 1 && (guard[1] !== id ||
|
||||
guard[2] !== exitChecksum(id, exit.code, exit.signal, exit.time).slice(0, 32))) return null;
|
||||
const conflictingName = exit?.version === 1 && namedExit && (exit.time !== namedExit.time ||
|
||||
exit.code !== namedExit.code || exit.signal !== namedExit.signal);
|
||||
return exit && { ...exit, file, namedExit: conflictingName ? namedExit : undefined };
|
||||
} finally {
|
||||
await handle.close();
|
||||
}
|
||||
} catch (error) {
|
||||
if (error.code === 'ENOENT') return;
|
||||
if (error.code || error instanceof SyntaxError) return null;
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = { isLegacyCapture: file => legacyCapture.test(path.basename(file)), isMetadataReceipt: file => Boolean(metadataReceipt(file)), receiptPath, publishedExits, publishedScriptStarts, readExit, writeExit, validExit, storageFull, retireLegacyFile, retiringExits };
|
||||
|
||||
if (require.main === module) {
|
||||
const id = process.env.QL_TRIGGER_ID;
|
||||
const exit = parseExit(id, JSON.parse(process.argv[2]));
|
||||
if (!idPattern.test(id || '') || !exit) throw new Error('Invalid supervisor exit receipt');
|
||||
const { code, signal, time } = exit;
|
||||
// An older supervisor may only have delivered this tuple in its message.
|
||||
// Journal it before waiting for the SQLite writer or loading the panel.
|
||||
let journaled = false;
|
||||
if (exit.version === 1) {
|
||||
try { writeExit(id, code, signal, time); journaled = Boolean(receiptPath(id)); }
|
||||
catch (error) { console.error('[scheduler] Could not journal supervisor message:', error); }
|
||||
}
|
||||
// Development workers run TypeScript directly. Released panels load the
|
||||
// compiled module without starting another runtime on ordinary exits.
|
||||
if (!fs.existsSync(path.join(__dirname, 'triggerHistory.js'))) {
|
||||
process.env.TS_NODE_PROJECT = path.join(__dirname, '../tsconfig.json');
|
||||
require('ts-node/register/transpile-only');
|
||||
}
|
||||
const { triggerHistory } = require('./triggerHistory');
|
||||
triggerHistory().complete(id, signal || code !== 0 ? 'failed' : 'finished',
|
||||
signal, code, time, exit.version === 1 ? exit : 'legacy').catch(error => {
|
||||
if (journaled && storageFull(error)) return;
|
||||
console.error('[scheduler] Failed to settle orphaned command:', error);
|
||||
process.exitCode = storageFull(error) ? 75 : 1;
|
||||
}).finally(() => require('../data').sequelize.close());
|
||||
}
|
||||
@@ -1,17 +1,16 @@
|
||||
import { Op } from 'sequelize';
|
||||
import { Query, QuerySpec, orderBy } from '../data/queries';
|
||||
import {
|
||||
SystemModel,
|
||||
AuthDataType,
|
||||
NotifyStatus,
|
||||
NotifyLogInfo,
|
||||
} from '../data/system';
|
||||
|
||||
// Both backend sends and script reports use the same bounded, best-effort sink.
|
||||
export async function persistNotificationAudit(
|
||||
info: NotifyLogInfo,
|
||||
): Promise<void> {
|
||||
try {
|
||||
await SystemModel.create({
|
||||
await SystemModel.insert({
|
||||
type: AuthDataType.notifyLog,
|
||||
info: {
|
||||
timestamp: Date.now(),
|
||||
@@ -27,19 +26,19 @@ export async function persistNotificationAudit(
|
||||
taskId: /^\d+$/.test(info.taskId || '') ? info.taskId : undefined,
|
||||
},
|
||||
});
|
||||
const oldest = await SystemModel.findAll({
|
||||
where: { type: AuthDataType.notifyLog },
|
||||
attributes: ['id'],
|
||||
order: [['id', 'DESC']],
|
||||
const oldest = await SystemModel.find(
|
||||
{ type: AuthDataType.notifyLog },
|
||||
{
|
||||
fields: ['id'],
|
||||
orderBy: orderBy([['id', 'DESC']]),
|
||||
offset: 200,
|
||||
limit: 1,
|
||||
});
|
||||
if (oldest[0]?.id) {
|
||||
await SystemModel.destroy({
|
||||
where: {
|
||||
type: AuthDataType.notifyLog,
|
||||
id: { [Op.lte]: oldest[0].id },
|
||||
},
|
||||
);
|
||||
if (oldest[0]?.id) {
|
||||
await SystemModel.nativeDelete({
|
||||
type: AuthDataType.notifyLog,
|
||||
id: { ['$lte']: oldest[0].id },
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
|
||||
+14
-45
@@ -1,9 +1,5 @@
|
||||
import { EventEmitter } from 'events';
|
||||
import PQueue, { QueueAddOptions } from 'p-queue-cjs';
|
||||
import os from 'os';
|
||||
import type { Sequelize } from 'sequelize';
|
||||
import { QueueOccupants, recordQueueAdmission } from './queueDiagnostics';
|
||||
import { CronWaitQueue, CronQueueOptions } from './cronWaitQueue';
|
||||
import { AuthDataType, SystemModel } from '../data/system';
|
||||
import Logger from '../loaders/logger';
|
||||
import { Dependence } from '../data/dependence';
|
||||
@@ -27,11 +23,7 @@ class TaskLimit {
|
||||
private queuedCrons = new Map<string, ICronFn<any>[]>();
|
||||
private repeatCronNotifyMap = new Map<string, number>();
|
||||
private updateLogLimit = new PQueue({ concurrency: 1 });
|
||||
private warnSampling = (error: Error) => Logger.warn('[queue] Could not save occupancy: %s', error.message);
|
||||
private scheduledOccupants = new QueueOccupants('scheduled', () => this.cronLimit.concurrency, this.warnSampling);
|
||||
private manualOccupants = new QueueOccupants('manual', () => this.manualCronoLimit.concurrency, this.warnSampling);
|
||||
private cronLimit = new PQueue<CronWaitQueue, CronQueueOptions>({
|
||||
queueClass: CronWaitQueue,
|
||||
private cronLimit = new PQueue({
|
||||
concurrency: Math.max(os.cpus().length, 4),
|
||||
});
|
||||
private manualCronoLimit = new PQueue({
|
||||
@@ -139,24 +131,26 @@ class TaskLimit {
|
||||
}
|
||||
}
|
||||
|
||||
public get cronConcurrency() {
|
||||
return this.manualCronoLimit.concurrency;
|
||||
}
|
||||
|
||||
public async setCustomLimit(limit?: number) {
|
||||
if (limit) {
|
||||
this.cronLimit.concurrency = limit;
|
||||
this.manualCronoLimit.concurrency = limit;
|
||||
this.scheduledOccupants.refresh();
|
||||
this.manualOccupants.refresh();
|
||||
return;
|
||||
}
|
||||
await SystemModel.sync();
|
||||
|
||||
try {
|
||||
const doc = await SystemModel.findOne({
|
||||
where: { type: AuthDataType.systemConfig },
|
||||
type: AuthDataType.systemConfig,
|
||||
});
|
||||
if (doc?.info?.cronConcurrency) {
|
||||
await this.setCustomLimit(doc.info.cronConcurrency);
|
||||
this.cronLimit.concurrency = doc.info.cronConcurrency;
|
||||
this.manualCronoLimit.concurrency = doc.info.cronConcurrency;
|
||||
}
|
||||
} catch (error) {
|
||||
// Imports can precede the isolated initializer on a fresh installation.
|
||||
// Use defaults until that initializer creates Auths; never create schema here.
|
||||
if ((error as { code?: string }).code !== 'DATABASE_SCHEMA_MISSING')
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -165,10 +159,6 @@ class TaskLimit {
|
||||
fn: ICronFn<T>,
|
||||
options?: Partial<QueueAddOptions>,
|
||||
isCurrent: () => boolean = () => true,
|
||||
onPending?: () => void,
|
||||
waitingSignal?: EventEmitter,
|
||||
triggerId?: string,
|
||||
db?: Sequelize,
|
||||
): Promise<T | void> {
|
||||
if (!isCurrent()) return;
|
||||
fn.cron = cron;
|
||||
@@ -177,10 +167,6 @@ class TaskLimit {
|
||||
const runs = this.queuedCrons
|
||||
.get(cron.id)
|
||||
?.filter((run) => run.isCurrent?.() !== false);
|
||||
if (cron.skip_if_pending && runs?.length) {
|
||||
onPending?.();
|
||||
return;
|
||||
}
|
||||
const result = runs?.length ? [...runs, fn] : [fn];
|
||||
const repeatTimes = this.repeatCronNotifyMap.get(cron.id) || 0;
|
||||
if (result?.length > 5) {
|
||||
@@ -211,31 +197,14 @@ class TaskLimit {
|
||||
return;
|
||||
}
|
||||
this.queuedCrons.set(cron.id, result);
|
||||
const run = this.trackAdmission(this.scheduledOccupants, this.cronLimit.concurrency, fn,
|
||||
{ id: triggerId, name: cron.name || cron.id }, db);
|
||||
if (!waitingSignal) return this.cronLimit.add(run, options);
|
||||
return new Promise<T | void>((resolve, reject) => {
|
||||
this.cronLimit.add(run, { ...options, waitingSignal, onRemoved: () => { this.scheduledOccupants.forget(triggerId); resolve(); } }).then(resolve, reject);
|
||||
});
|
||||
}
|
||||
|
||||
private trackAdmission<T>(pool: QueueOccupants, limit: number, fn: () => Promise<T>, occupant: { id?: string; name: string }, db?: Sequelize) {
|
||||
const admission = pool.admission(limit);
|
||||
if (occupant.id && admission && db) {
|
||||
pool.watch(occupant.id, db);
|
||||
void recordQueueAdmission(db, occupant.id, admission)
|
||||
.catch(error => Logger.warn('[queue] Failed to record wait reason: %s', error.message));
|
||||
}
|
||||
return pool.track(fn, occupant, db);
|
||||
return this.cronLimit.add(fn, options);
|
||||
}
|
||||
|
||||
public async manualRunWithCronLimit<T>(
|
||||
fn: () => Promise<T>,
|
||||
options?: Partial<QueueAddOptions>,
|
||||
occupant: { id?: string; name: string } = { name: '—' },
|
||||
db?: Sequelize,
|
||||
): Promise<T | void> {
|
||||
return this.manualCronoLimit.add(this.trackAdmission(this.manualOccupants, this.manualCronoLimit.concurrency, fn, occupant, db), options);
|
||||
return this.manualCronoLimit.add(fn, options);
|
||||
}
|
||||
|
||||
public async runWithSubscriptionLimit<T>(
|
||||
|
||||
@@ -1,127 +0,0 @@
|
||||
import { QueryTypes, Sequelize } from 'sequelize';
|
||||
|
||||
type Occupant = { id?: string; name: string };
|
||||
export type Admission = {
|
||||
queue: 'manual' | 'scheduled';
|
||||
limit: number;
|
||||
occupied: number;
|
||||
holders: Occupant[];
|
||||
};
|
||||
|
||||
// Each object belongs to exactly one execution pool in its owning process.
|
||||
export class QueueOccupants {
|
||||
private active = new Set<Occupant>();
|
||||
private waiting = new Map<string, Sequelize>();
|
||||
private writing = false;
|
||||
private changed = false;
|
||||
|
||||
constructor(
|
||||
private queue: Admission['queue'],
|
||||
private limit: () => number,
|
||||
private warn: (error: Error) => void,
|
||||
) {}
|
||||
|
||||
watch(id: string, db: Sequelize) {
|
||||
this.waiting.set(id, db);
|
||||
this.refresh();
|
||||
}
|
||||
|
||||
forget(id?: string) {
|
||||
if (id) this.waiting.delete(id);
|
||||
}
|
||||
|
||||
refresh() {
|
||||
if (!this.waiting.size) return;
|
||||
this.changed = true;
|
||||
if (this.writing) return;
|
||||
this.writing = true;
|
||||
// Coalesce synchronous PQueue handoffs and keep SQLite writes in observation order.
|
||||
void Promise.resolve().then(async () => {
|
||||
try {
|
||||
while (this.changed) {
|
||||
this.changed = false;
|
||||
const context = JSON.stringify(this.snapshot(this.limit()));
|
||||
const groups = new Map<Sequelize, string[]>();
|
||||
for (const [id, db] of this.waiting) {
|
||||
const ids = groups.get(db);
|
||||
if (ids) ids.push(id);
|
||||
else groups.set(db, [id]);
|
||||
}
|
||||
for (const [db, ids] of groups) {
|
||||
await db
|
||||
.query(
|
||||
`UPDATE CronTriggers SET queue_live_context=$context
|
||||
WHERE state='queued' AND dequeued_at IS NULL AND id IN (SELECT value FROM json_each($ids))`,
|
||||
{ bind: { context, ids: JSON.stringify(ids) } },
|
||||
)
|
||||
.catch(this.warn);
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
this.writing = false;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
admission(limit: number): Admission | undefined {
|
||||
return this.active.size >= limit ? this.snapshot(limit) : undefined;
|
||||
}
|
||||
|
||||
private snapshot(limit: number): Admission {
|
||||
return {
|
||||
queue: this.queue,
|
||||
limit,
|
||||
occupied: this.active.size,
|
||||
holders: [...this.active].slice(0, 8),
|
||||
};
|
||||
}
|
||||
|
||||
track<T>(job: () => Promise<T>, occupant: Occupant, db?: Sequelize) {
|
||||
return async () => {
|
||||
this.forget(occupant.id);
|
||||
this.active.add(occupant);
|
||||
this.refresh();
|
||||
if (occupant.id && db) {
|
||||
void db
|
||||
.query(
|
||||
'UPDATE CronTriggers SET dequeued_at=$at,queue_live_context=NULL WHERE id=$id AND queued_at <= $at AND dequeued_at IS NULL',
|
||||
{ bind: { id: occupant.id, at: Date.now() } },
|
||||
)
|
||||
.catch(this.warn);
|
||||
}
|
||||
try {
|
||||
return await job();
|
||||
} finally {
|
||||
this.active.delete(occupant);
|
||||
this.refresh();
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
export function recordQueueAdmission(
|
||||
db: Sequelize,
|
||||
id: string,
|
||||
admission: Admission,
|
||||
) {
|
||||
return db.query(
|
||||
'UPDATE CronTriggers SET queue_context=$context WHERE id=$id AND queued_at <= $at AND queue_context IS NULL',
|
||||
{ bind: { id, at: Date.now(), context: JSON.stringify(admission) } },
|
||||
);
|
||||
}
|
||||
|
||||
export function oldestQueued(db: Sequelize) {
|
||||
return db.query<{
|
||||
id: string;
|
||||
name: string;
|
||||
source: string;
|
||||
queued_at: number;
|
||||
queue_context: string | null;
|
||||
queue_live_context: string | null;
|
||||
}>(
|
||||
`SELECT t.id, COALESCE(NULLIF(c.name,''), c.command, '#' || t.cron_id) AS name, t.source,t.queued_at,t.queue_context,t.queue_live_context
|
||||
FROM CronTriggers t LEFT JOIN Crontabs c ON c.id=t.cron_id
|
||||
WHERE t.state='queued' AND t.dequeued_at IS NULL AND t.queued_at IS NOT NULL ORDER BY t.queued_at,t.id LIMIT 25`,
|
||||
{ type: QueryTypes.SELECT },
|
||||
);
|
||||
}
|
||||
+27
-174
@@ -1,156 +1,63 @@
|
||||
import { hasLiveCronProcess } from './cronProcess';
|
||||
import { EventEmitter } from 'events';
|
||||
import PQueue from 'p-queue-cjs';
|
||||
import { triggerHistory, TriggerState } from './triggerHistory';
|
||||
import { t } from './i18n';
|
||||
import { spawnCronCommand, releaseCronCommand } from './cronCommandProcess';
|
||||
import { spawn } from 'cross-spawn';
|
||||
import taskLimit from './pLimit';
|
||||
import Logger from '../loaders/logger';
|
||||
import { ICron } from '../protos/cron';
|
||||
import { CrontabModel, CrontabStatus } from '../data/cron';
|
||||
import { killTask } from '../config/util';
|
||||
import { RunningInstanceModel, InstanceStatus } from '../data/runningInstance';
|
||||
import dayjs from 'dayjs';
|
||||
import { observeChildProcess, asError } from './childProcess';
|
||||
|
||||
const waiting = new Map<string, () => void>();
|
||||
// A backlog of missed timers can otherwise open hundreds of competing SQLite
|
||||
// writer transactions on wake. Only serialize history writes, never commands.
|
||||
const historyWrites = new PQueue({ concurrency: 1 });
|
||||
export function cancelWaitingTriggers(ids: string[]) {
|
||||
for (const id of ids) waiting.get(id)?.();
|
||||
}
|
||||
|
||||
export async function runCron(
|
||||
export function runCron(
|
||||
cmd: string,
|
||||
cron: ICron,
|
||||
isCurrent: () => boolean = () => true,
|
||||
trigger?: { id: string; time: number; source: 'node' | 'recovery' },
|
||||
): Promise<number | void> {
|
||||
const history = trigger && triggerHistory();
|
||||
const queuedAt = Date.now();
|
||||
if (trigger && history) {
|
||||
const cronId = Number(cron.id);
|
||||
const admitted = await historyWrites.add(() => cron.skip_if_pending
|
||||
? history.enqueueUnlessPending(trigger.id, cronId, trigger.source, trigger.time, queuedAt, cron.recovery_from)
|
||||
: history.enqueue(trigger.id, cronId, trigger.source, trigger.time, queuedAt));
|
||||
if (!admitted) return;
|
||||
}
|
||||
let reason = 'capacity';
|
||||
let state: TriggerState = 'skipped';
|
||||
let exitCode: number | null = null;
|
||||
let claimed = false;
|
||||
const deadline = cron.max_queue_wait ? queuedAt + cron.max_queue_wait * 1000 : Infinity;
|
||||
let timer: NodeJS.Timeout | undefined;
|
||||
const expiry = trigger ? new EventEmitter() : undefined;
|
||||
const alive = () => isCurrent() && Date.now() < deadline;
|
||||
if (trigger && expiry && Number.isFinite(deadline)) {
|
||||
timer = setTimeout(() => {
|
||||
reason = 'queue_timeout';
|
||||
taskLimit.removeQueuedCron(cron.id, execute);
|
||||
expiry.emit('expired');
|
||||
}, Math.max(0, deadline - Date.now()));
|
||||
timer.unref();
|
||||
}
|
||||
const execute = async () => {
|
||||
if (trigger) waiting.delete(trigger.id);
|
||||
reason = 'changed';
|
||||
try {
|
||||
if (!alive()) { reason = isCurrent() ? 'queue_timeout' : 'changed'; return; }
|
||||
let multiple = false;
|
||||
// A single-instance trigger must not interrupt work already in progress.
|
||||
if (!isCurrent()) return;
|
||||
// Check if the cron is already running and stop it (only if multiple instances are not allowed)
|
||||
try {
|
||||
const existingCron = await CrontabModel.findOne({
|
||||
where: { id: Number(cron.id) },
|
||||
id: Number(cron.id),
|
||||
});
|
||||
|
||||
// A mutation may commit while this queued run is reading the database.
|
||||
if (!isCurrent() || !existingCron || existingCron.isDisabled) return;
|
||||
|
||||
// Default to single instance mode (0) for backward compatibility
|
||||
multiple = existingCron.allow_multiple_instances === 1;
|
||||
const allowSingleInstances =
|
||||
existingCron?.allow_multiple_instances === 0;
|
||||
|
||||
if (!multiple) {
|
||||
// A queued manual run is an active reservation, even if its stored PID
|
||||
// belongs to a previous execution.
|
||||
if (
|
||||
existingCron.status === CrontabStatus.queued &&
|
||||
existingCron.pid
|
||||
allowSingleInstances &&
|
||||
existingCron &&
|
||||
existingCron.pid &&
|
||||
(existingCron.status === CrontabStatus.running ||
|
||||
existingCron.status === CrontabStatus.queued)
|
||||
) {
|
||||
Logger.info(
|
||||
'[schedule][Skip queued single-instance task] Task ID: %s, PID: %s',
|
||||
t('[schedule][停止已运行任务] 任务ID: %s, PID: %s'),
|
||||
cron.id,
|
||||
existingCron.pid,
|
||||
);
|
||||
reason = 'overlap';
|
||||
return;
|
||||
}
|
||||
if (
|
||||
existingCron.status === CrontabStatus.running &&
|
||||
existingCron.pid
|
||||
) {
|
||||
if (hasLiveCronProcess(existingCron.status, existingCron.pid)) {
|
||||
Logger.info(
|
||||
'[schedule][Skip active single-instance task] Task ID: %s, PID: %s',
|
||||
cron.id,
|
||||
existingCron.pid,
|
||||
);
|
||||
reason = 'overlap';
|
||||
return;
|
||||
}
|
||||
|
||||
// Capture old instance IDs before releasing the stale cron state so
|
||||
// a concurrent replacement cannot have its instance marked stopped.
|
||||
const staleInstances = await RunningInstanceModel.findAll({
|
||||
attributes: ['id'],
|
||||
where: {
|
||||
await killTask(existingCron.pid, true);
|
||||
// Mark old running instances as stopped
|
||||
const stoppedAt = dayjs().unix();
|
||||
await RunningInstanceModel.nativeUpdate(
|
||||
{
|
||||
cron_id: Number(cron.id),
|
||||
pid: existingCron.pid,
|
||||
status: InstanceStatus.running,
|
||||
},
|
||||
});
|
||||
if (!isCurrent()) return;
|
||||
const [recovered] = await CrontabModel.update(
|
||||
{
|
||||
status: CrontabStatus.idle,
|
||||
pid: null,
|
||||
queued_token: null,
|
||||
} as any,
|
||||
{
|
||||
where: {
|
||||
id: Number(cron.id),
|
||||
pid: existingCron.pid,
|
||||
status: CrontabStatus.running,
|
||||
...(existingCron.log_path !== undefined
|
||||
? { log_path: existingCron.log_path }
|
||||
: {}),
|
||||
...(existingCron.queued_token !== undefined
|
||||
? { queued_token: existingCron.queued_token }
|
||||
: {}),
|
||||
...(existingCron.last_execution_time !== undefined
|
||||
? { last_execution_time: existingCron.last_execution_time }
|
||||
: {}),
|
||||
...(existingCron.isDisabled !== undefined
|
||||
? { isDisabled: existingCron.isDisabled }
|
||||
: {}),
|
||||
allow_multiple_instances: 0,
|
||||
},
|
||||
},
|
||||
{ status: InstanceStatus.stopped, finished_at: stoppedAt },
|
||||
);
|
||||
if (recovered !== 1) return;
|
||||
const staleIds = staleInstances.map((instance) => instance.id!);
|
||||
if (staleIds.length) {
|
||||
await RunningInstanceModel.update(
|
||||
{ status: InstanceStatus.stopped, finished_at: dayjs().unix() },
|
||||
{ where: { id: staleIds, status: InstanceStatus.running } },
|
||||
// Update the status to idle after killing
|
||||
await CrontabModel.nativeUpdate(
|
||||
{ id: Number(cron.id) },
|
||||
{ status: CrontabStatus.idle, pid: undefined },
|
||||
);
|
||||
}
|
||||
Logger.info(
|
||||
'[schedule][Recovered stale single-instance task] Task ID: %s, PID: %s',
|
||||
cron.id,
|
||||
existingCron.pid,
|
||||
);
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
Logger.error(
|
||||
t('[schedule][检查已运行任务失败] 任务ID: %s, 错误: %s'),
|
||||
@@ -160,7 +67,7 @@ export async function runCron(
|
||||
throw error;
|
||||
}
|
||||
|
||||
// Invalidation can happen during the asynchronous database check.
|
||||
// In particular, invalidation can happen while stopping a previous run.
|
||||
if (!isCurrent()) return;
|
||||
Logger.info(
|
||||
t('[schedule][开始执行任务] 参数 %s'),
|
||||
@@ -169,39 +76,9 @@ export async function runCron(
|
||||
command: cmd,
|
||||
}),
|
||||
);
|
||||
clearTimeout(timer);
|
||||
if (Date.now() >= deadline) {
|
||||
reason = 'queue_timeout';
|
||||
return;
|
||||
}
|
||||
if (trigger) {
|
||||
claimed = await history!.start(trigger.id, Date.now(), multiple);
|
||||
if (!claimed) { reason = 'overlap'; return; }
|
||||
}
|
||||
if (!isCurrent() || Date.now() >= deadline) {
|
||||
reason = isCurrent() ? 'queue_timeout' : 'changed';
|
||||
return;
|
||||
}
|
||||
let saveStart: Promise<void> | undefined;
|
||||
const cp = spawnCronCommand(cmd, trigger?.id, trigger && history ? at => {
|
||||
saveStart = history.recordCommandStart(trigger.id, at).catch(error => {
|
||||
Logger.warn('[schedule] Could not record command start: %s', asError(error).message);
|
||||
});
|
||||
} : undefined);
|
||||
const cp = spawn(cmd, { shell: '/bin/bash' });
|
||||
|
||||
let denied: string | undefined;
|
||||
const { completed } = observeChildProcess(cp, {
|
||||
onStart: async () => {
|
||||
if (!trigger) return;
|
||||
try {
|
||||
if (await history!.bindCommand(trigger.id, cp.pid!) && !await history!.shouldStop(trigger.id)) {
|
||||
if (!alive()) denied = isCurrent() ? 'queue_timeout' : 'changed';
|
||||
else await releaseCronCommand(cp);
|
||||
}
|
||||
} finally {
|
||||
cp.stdin.end();
|
||||
}
|
||||
},
|
||||
onStderr: async (message) => {
|
||||
Logger.info(
|
||||
t('[schedule][任务标准错误] 命令: %s, 信息: %s'),
|
||||
@@ -211,11 +88,6 @@ export async function runCron(
|
||||
},
|
||||
});
|
||||
const result = await completed;
|
||||
await saveStart;
|
||||
if (denied) { reason = denied; return; }
|
||||
state = result.signal ? 'stopped' : result.error || result.code !== 0 ? 'failed' : 'finished';
|
||||
reason = result.error ? 'spawn' : result.signal || '';
|
||||
exitCode = result.code;
|
||||
if (result.error) {
|
||||
Logger.error(
|
||||
t('[schedule][执行任务失败] 命令: %s, 错误: %s'),
|
||||
@@ -230,8 +102,6 @@ export async function runCron(
|
||||
);
|
||||
return { ...cron, command: cmd, pid: cp.pid, ...result } as any;
|
||||
} catch (error) {
|
||||
state = 'failed';
|
||||
reason = 'spawn';
|
||||
Logger.error(
|
||||
t('[schedule][创建任务失败] 命令: %s, 错误: %s'),
|
||||
cmd,
|
||||
@@ -241,22 +111,5 @@ export async function runCron(
|
||||
taskLimit.removeQueuedCron(cron.id, execute);
|
||||
}
|
||||
};
|
||||
try {
|
||||
if (trigger && expiry) waiting.set(trigger.id, () => {
|
||||
taskLimit.removeQueuedCron(cron.id, execute);
|
||||
expiry.emit('expired');
|
||||
});
|
||||
return await taskLimit.runWithCronLimit(cron, execute, undefined, isCurrent, () => { reason = 'pending'; }, expiry, trigger?.id, CrontabModel.sequelize);
|
||||
} finally {
|
||||
clearTimeout(timer);
|
||||
if (trigger) waiting.delete(trigger.id);
|
||||
if (trigger && history) {
|
||||
const outcomeReason = state === 'skipped' && !isCurrent() ? 'changed' : reason;
|
||||
const finishedAt = Date.now();
|
||||
await historyWrites.add(() => state === 'skipped' && !claimed
|
||||
? history.skipQueued(trigger.id, outcomeReason, finishedAt)
|
||||
: history.complete(trigger.id, state, outcomeReason || null, exitCode, finishedAt),
|
||||
{ priority: 1 });
|
||||
}
|
||||
}
|
||||
return taskLimit.runWithCronLimit(cron, execute, undefined, isCurrent);
|
||||
}
|
||||
|
||||
@@ -28,7 +28,7 @@ const backend = read(path.resolve(__dirname, '../app.js'));
|
||||
const root = process.env.QL_DIR || path.resolve(__dirname, '../../..');
|
||||
const version = read(path.join(root, 'version.yaml'))
|
||||
?.toString()
|
||||
.match(/^\uFEFF?version:\s*["']?(\d+\.\d+\.\d+(?:-[\w.-]+)?(?:\+[\w.-]+)?)/m)?.[1];
|
||||
.match(/^\uFEFF?version:\s*["']?(\d+\.\d+\.\d+)/m)?.[1];
|
||||
|
||||
export const runtimeBuild = Object.freeze({
|
||||
instanceId: randomUUID(),
|
||||
|
||||
@@ -1,289 +0,0 @@
|
||||
import { QueryTypes, Sequelize, Transaction } from 'sequelize';
|
||||
import { AddCronRequest, DeleteCronRequest } from '../protos/cron';
|
||||
import { upcomingSlots } from './cronScheduler';
|
||||
import { slotId } from './triggerHistory';
|
||||
|
||||
type Rule = {
|
||||
cron_id: string;
|
||||
rule_index: number;
|
||||
schedule: string;
|
||||
zone: string;
|
||||
since: number;
|
||||
until: number | null;
|
||||
open_latest: number;
|
||||
close_latest: number;
|
||||
};
|
||||
type Receipt = {
|
||||
id: string;
|
||||
cron_id: number;
|
||||
scheduled_at: number;
|
||||
observed_at: number;
|
||||
state: string;
|
||||
command_started_at: number | null;
|
||||
verified_exit: number;
|
||||
script_started_at: number | null;
|
||||
queued_at: number | null;
|
||||
started_at: number | null;
|
||||
};
|
||||
|
||||
export async function saveSchedulePlan(
|
||||
db: Sequelize,
|
||||
change: AddCronRequest | DeleteCronRequest,
|
||||
at?: number,
|
||||
token?: string,
|
||||
) {
|
||||
const rules =
|
||||
'crons' in change
|
||||
? [
|
||||
...new Map(change.crons.map((task) => [task.id, task])).values(),
|
||||
].flatMap((task) =>
|
||||
[
|
||||
task.schedule,
|
||||
...(task.extra_schedules || []).map((extra) => extra.schedule),
|
||||
].map((schedule, index) => ({ task: task.id, index, schedule })),
|
||||
)
|
||||
: [];
|
||||
const ids =
|
||||
'crons' in change ? change.crons.map((task) => task.id) : change.ids;
|
||||
const replace = 'replace' in change && change.replace;
|
||||
await db.transaction(async (transaction) => {
|
||||
const now = at ?? Date.now();
|
||||
const bind = {
|
||||
rules: JSON.stringify(rules),
|
||||
ids: JSON.stringify(ids),
|
||||
replace: Number(replace),
|
||||
zone: Intl.DateTimeFormat().resolvedOptions().timeZone,
|
||||
now,
|
||||
token: token ?? null,
|
||||
};
|
||||
if (token)
|
||||
await db.query(
|
||||
'INSERT INTO CronPlanSwitches(token,staged_at) VALUES($token,$now)',
|
||||
{ transaction, bind: { token, now } },
|
||||
);
|
||||
if (replace)
|
||||
await db.query(
|
||||
'INSERT OR IGNORE INTO CronPlanCoverage(id,since) VALUES(1,$now)',
|
||||
{ transaction, bind: { now } },
|
||||
);
|
||||
const desired = `WITH desired AS (SELECT json_extract(value,'$.task') AS task, json_extract(value,'$.index') AS idx,
|
||||
json_extract(value,'$.schedule') AS schedule FROM json_each($rules))`;
|
||||
await db.query(
|
||||
`${desired} UPDATE CronPlanRules SET until=$now,closed_by=$token WHERE until IS NULL
|
||||
AND ($replace OR cron_id IN (SELECT value FROM json_each($ids)))
|
||||
AND (cron_id,rule_index,schedule,zone) NOT IN (SELECT task,idx,schedule,$zone FROM desired)`,
|
||||
{ transaction, bind },
|
||||
);
|
||||
await db.query(
|
||||
`${desired} INSERT OR IGNORE INTO CronPlanRules(cron_id,rule_index,schedule,zone,since,opened_by)
|
||||
SELECT task,idx,schedule,$zone,$now,$token FROM desired`,
|
||||
{
|
||||
transaction,
|
||||
bind: { rules: bind.rules, zone: bind.zone, now, token: bind.token },
|
||||
},
|
||||
);
|
||||
// Only the current local day is displayed. Keep an extra day for zone changes.
|
||||
await db.query(
|
||||
`DELETE FROM CronPlanRules WHERE until < $now - 3*86400000 AND
|
||||
(closed_by IS NULL OR closed_by IN (SELECT token FROM CronPlanSwitches WHERE last_at < $now - 3*86400000))`,
|
||||
{ transaction, bind: { now } },
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
// Persisting intent and installing timers are separated by an asynchronous
|
||||
// SQLite commit. Only the synchronous timer swap defines the effective edges.
|
||||
export async function confirmSchedulePlan(
|
||||
db: Sequelize,
|
||||
token: string,
|
||||
first: number,
|
||||
last: number,
|
||||
replace: boolean,
|
||||
) {
|
||||
await db.transaction(async (transaction) => {
|
||||
await db.query(
|
||||
`UPDATE CronPlanSwitches SET first_at=$first,last_at=$last
|
||||
WHERE token=$token AND last_at IS NULL`,
|
||||
{ transaction, bind: { token, first, last } },
|
||||
);
|
||||
if (replace) {
|
||||
// After a crash the former worker's switch time is unknowable. A complete
|
||||
// replacement establishes the latest possible edge for older requests.
|
||||
await db.query(
|
||||
`UPDATE CronPlanSwitches SET first_at=staged_at,last_at=$last
|
||||
WHERE last_at IS NULL AND seq<(SELECT seq FROM CronPlanSwitches WHERE token=$token)`,
|
||||
{ transaction, bind: { token, last } },
|
||||
);
|
||||
}
|
||||
await db.query(
|
||||
`DELETE FROM CronPlanSwitches WHERE last_at < $last - 3*86400000
|
||||
AND token NOT IN (SELECT opened_by FROM CronPlanRules WHERE opened_by IS NOT NULL)
|
||||
AND token NOT IN (SELECT closed_by FROM CronPlanRules WHERE closed_by IS NOT NULL)`,
|
||||
{ transaction, bind: { last } },
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
export const blockSize = 15 * 60000;
|
||||
const calendar = new Map<string, number[]>();
|
||||
export function blockSlots(schedule: string, zone: string, block: number) {
|
||||
const key = JSON.stringify([zone, schedule, block]);
|
||||
let times = calendar.get(key);
|
||||
if (!times) {
|
||||
times = upcomingSlots(schedule, block - 1, Infinity, block + blockSize - 1);
|
||||
if (calendar.size >= 2048) calendar.delete(calendar.keys().next().value!);
|
||||
calendar.set(key, times);
|
||||
}
|
||||
return times;
|
||||
}
|
||||
|
||||
function lowerBound(times: number[], time: number) {
|
||||
let lo = 0,
|
||||
hi = times.length;
|
||||
while (lo < hi) {
|
||||
const mid = Math.floor((lo + hi) / 2);
|
||||
if (times[mid] < time) lo = mid + 1;
|
||||
else hi = mid;
|
||||
}
|
||||
return lo;
|
||||
}
|
||||
|
||||
function p95(values: number[]) {
|
||||
return values.length
|
||||
? values.sort((a, b) => a - b)[Math.ceil(values.length * 0.95) - 1]
|
||||
: null;
|
||||
}
|
||||
|
||||
export async function auditSchedule(
|
||||
db: Sequelize,
|
||||
dayStart: number,
|
||||
now = Date.now(),
|
||||
) {
|
||||
// All counts use the same settled plan window and the same committed snapshot.
|
||||
const nextDay = new Date(dayStart);
|
||||
nextDay.setHours(24, 0, 0, 0);
|
||||
const through = Math.min(now - 5000, nextDay.getTime() - 1);
|
||||
const snapshot = await db.transaction(
|
||||
{ type: Transaction.TYPES.DEFERRED },
|
||||
async (transaction) => {
|
||||
const [coverage] = await db.query<{ since: number }>(
|
||||
`SELECT MAX(since,$dayStart,
|
||||
COALESCE((SELECT cutoff FROM CronHistoryRetention WHERE id=1),0)) AS since FROM CronPlanCoverage WHERE id=1`,
|
||||
{ transaction, bind: { dayStart }, type: QueryTypes.SELECT },
|
||||
);
|
||||
if (!coverage || coverage.since > through) return;
|
||||
const bind = { since: coverage.since, through };
|
||||
const rules = await db.query<Rule>(
|
||||
`SELECT r.cron_id,r.rule_index,r.schedule,r.zone,COALESCE(o.first_at,r.since) AS since,
|
||||
CASE WHEN o.token IS NULL THEN r.since ELSE COALESCE(o.last_at,$through) END AS open_latest,
|
||||
COALESCE(c.first_at,r.until) AS until,
|
||||
CASE WHEN c.token IS NULL THEN COALESCE(r.until,$through) ELSE COALESCE(c.last_at,$through) END AS close_latest
|
||||
FROM CronPlanRules r LEFT JOIN CronPlanSwitches o ON o.token=r.opened_by
|
||||
LEFT JOIN CronPlanSwitches c ON c.token=r.closed_by
|
||||
WHERE r.since < $through AND close_latest >= $since`,
|
||||
{ transaction, bind, type: QueryTypes.SELECT },
|
||||
);
|
||||
const receipts = await db.query<Receipt>(
|
||||
`SELECT id,cron_id,scheduled_at,observed_at,state,
|
||||
command_started_at,script_started_at,queued_at,COALESCE(dequeued_at,started_at) AS started_at,
|
||||
EXISTS(SELECT 1 FROM CronLegacyExitBookings b WHERE b.trigger_id=CronTriggers.id AND b.bound=1) AS verified_exit FROM CronTriggers
|
||||
WHERE scheduled_at BETWEEN $since AND $through AND source IN ('node','recovery')`,
|
||||
{ transaction, bind, type: QueryTypes.SELECT },
|
||||
);
|
||||
return { since: coverage.since, rules, receipts };
|
||||
},
|
||||
);
|
||||
if (!snapshot) return null;
|
||||
const byTaskBlock = new Map<string, Receipt[]>();
|
||||
for (const row of snapshot.receipts) {
|
||||
const block = row.scheduled_at - (row.scheduled_at % blockSize);
|
||||
const key = row.cron_id + '/' + block;
|
||||
const group = byTaskBlock.get(key);
|
||||
if (group) group.push(row);
|
||||
else byTaskBlock.set(key, [row]);
|
||||
}
|
||||
const deviations: number[] = [],
|
||||
starts: number[] = [],
|
||||
entries: number[] = [],
|
||||
waits: number[] = [];
|
||||
const zone = Intl.DateTimeFormat().resolvedOptions().timeZone;
|
||||
let partial = false;
|
||||
let expected = 0,
|
||||
onTime = 0,
|
||||
skipped = 0,
|
||||
queued = 0,
|
||||
dispatched = 0;
|
||||
for (const rule of snapshot.rules) {
|
||||
const first = Math.max(snapshot.since, rule.since + 1);
|
||||
const last = Math.min(through, rule.close_latest);
|
||||
const certainFirst = Math.max(first, rule.open_latest + 1);
|
||||
const certainLast = Math.min(last, rule.until ?? last);
|
||||
if (first > last) continue;
|
||||
// A wall clock rule registered in another time zone cannot be replayed
|
||||
// against the current local calendar.
|
||||
if (rule.zone !== zone) return null;
|
||||
for (
|
||||
let block = first - (first % blockSize);
|
||||
block <= last;
|
||||
block += blockSize
|
||||
) {
|
||||
const times = blockSlots(rule.schedule, zone, block);
|
||||
const possible = lowerBound(times, last + 1) - lowerBound(times, first);
|
||||
const certain = Math.max(
|
||||
0,
|
||||
lowerBound(times, certainLast + 1) - lowerBound(times, certainFirst),
|
||||
);
|
||||
if (certain < possible) partial = true;
|
||||
expected += certain;
|
||||
for (const row of byTaskBlock.get(rule.cron_id + '/' + block) ?? []) {
|
||||
const time = row.scheduled_at;
|
||||
if (
|
||||
time < certainFirst ||
|
||||
time > certainLast ||
|
||||
times[lowerBound(times, time)] !== time ||
|
||||
row.id !== slotId(rule.cron_id, rule.rule_index, rule.schedule, time)
|
||||
)
|
||||
continue;
|
||||
const deviation = Math.abs(row.observed_at - time);
|
||||
deviations.push(deviation);
|
||||
if (deviation <= 5000) onTime++;
|
||||
if (
|
||||
row.command_started_at != null ||
|
||||
row.script_started_at != null ||
|
||||
row.verified_exit
|
||||
) {
|
||||
dispatched++;
|
||||
if (row.command_started_at != null && row.command_started_at >= time)
|
||||
starts.push(row.command_started_at - time);
|
||||
} else if (row.state === 'skipped') skipped++;
|
||||
else if (row.state === 'queued') queued++;
|
||||
if (row.script_started_at != null && row.script_started_at >= time)
|
||||
entries.push(row.script_started_at - time);
|
||||
if (row.started_at != null && row.queued_at != null && row.started_at >= row.queued_at)
|
||||
waits.push(row.started_at - row.queued_at);
|
||||
}
|
||||
}
|
||||
}
|
||||
const observed = deviations.length;
|
||||
return {
|
||||
since: snapshot.since,
|
||||
through,
|
||||
zone,
|
||||
partial,
|
||||
expected,
|
||||
observed,
|
||||
missing: expected - observed,
|
||||
onTime,
|
||||
skipped,
|
||||
queued,
|
||||
dispatched,
|
||||
commandSamples: starts.length,
|
||||
unconfirmed: observed - dispatched - skipped - queued,
|
||||
triggerDeviationP95: p95(deviations),
|
||||
waitP95: p95(waits),
|
||||
waitSamples: waits.length,
|
||||
commandStartP95: p95(starts),
|
||||
scriptStartP95: p95(entries),
|
||||
scriptSamples: entries.length,
|
||||
};
|
||||
}
|
||||
@@ -1,9 +1,4 @@
|
||||
import dayjs from 'dayjs';
|
||||
import { installTriggerHistory } from './triggerHistory';
|
||||
import { repairLegacyDailyStatistics } from './legacyDailyStatistics';
|
||||
import { QueryTypes, Sequelize } from 'sequelize';
|
||||
|
||||
export const prunedExitMigrationId = 'preserve-pruned-bound-exits-v1';
|
||||
import { DatabaseClient } from '../data/databaseClient';
|
||||
|
||||
// Append new entries; IDs are persisted and must not be renumbered or reused.
|
||||
const columns = [
|
||||
@@ -30,35 +25,21 @@ const columns = [
|
||||
{ table: 'Envs', column: 'isPinned', type: 'NUMBER' },
|
||||
{ table: 'Envs', column: 'labels', type: 'JSON' },
|
||||
{ table: 'Crontabs', column: 'queued_token', type: 'VARCHAR(255)' },
|
||||
{ table: 'Crontabs', column: 'max_queue_wait', type: 'INTEGER' },
|
||||
{ table: 'Crontabs', column: 'catchup_seconds', type: 'INTEGER' },
|
||||
{ table: 'Crontabs', column: 'skip_if_pending', type: 'BOOLEAN' },
|
||||
{ table: 'Crontabs', column: 'recovery_from', type: 'BIGINT' },
|
||||
{ table: 'Crontabs', column: 'last_instance_id', type: 'INTEGER' },
|
||||
{ table: 'CrontabStats', column: 'untimed_count', type: 'INTEGER NOT NULL DEFAULT 0' },
|
||||
{ table: 'CrontabStats', column: 'fixed_max_time', type: 'NUMBER' },
|
||||
];
|
||||
|
||||
export async function migrateSchema(database: Sequelize): Promise<void> {
|
||||
await database.transaction(async (transaction) => {
|
||||
export async function migrateSchema(database: DatabaseClient): Promise<void> {
|
||||
await database.transaction(async () => {
|
||||
await database.query(
|
||||
'CREATE TABLE IF NOT EXISTS "SchemaMigrations" ("id" TEXT PRIMARY KEY, "applied_at" TEXT NOT NULL)',
|
||||
{ transaction },
|
||||
);
|
||||
await installTriggerHistory(database, transaction);
|
||||
const applied = await database.query<{ id: string }>(
|
||||
'SELECT "id" FROM "SchemaMigrations"',
|
||||
{ type: QueryTypes.SELECT, transaction },
|
||||
);
|
||||
const appliedIds = new Set(applied.map(({ id }) => id));
|
||||
for (const { table, column, type } of columns) {
|
||||
const id = `add-${table}-${column}`;
|
||||
const fields = await database.query<{ name: string }>(
|
||||
`PRAGMA table_info("${table}")`,
|
||||
{
|
||||
type: QueryTypes.SELECT,
|
||||
transaction,
|
||||
},
|
||||
);
|
||||
if (fields.length === 0)
|
||||
throw new Error(`Migration table is missing: ${table}`);
|
||||
@@ -66,65 +47,14 @@ export async function migrateSchema(database: Sequelize): Promise<void> {
|
||||
// table/column/type come only from the static migration manifest above.
|
||||
await database.query(
|
||||
`ALTER TABLE "${table}" ADD COLUMN "${column}" ${type}`,
|
||||
{ transaction },
|
||||
);
|
||||
}
|
||||
if (!appliedIds.has(id)) {
|
||||
await database.query(
|
||||
'INSERT INTO "SchemaMigrations" ("id", "applied_at") VALUES (:id, :appliedAt)',
|
||||
{
|
||||
replacements: { id, appliedAt: new Date().toISOString() },
|
||||
transaction,
|
||||
},
|
||||
'INSERT INTO "SchemaMigrations" ("id", "applied_at") VALUES (?, ?)',
|
||||
[id, new Date().toISOString()],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
const repairId = 'repair-legacy-daily-statistics-v3';
|
||||
const prior = appliedIds.has('repair-legacy-daily-statistics-v2') ? 2
|
||||
: appliedIds.has('repair-legacy-daily-statistics-v1') ? 1 : 0;
|
||||
const retentionId = 'preserve-cron-stat-retention-v1';
|
||||
if (!appliedIds.has(retentionId)) {
|
||||
if (prior || appliedIds.has(repairId)) {
|
||||
// Old cleanup removed complete date prefixes but kept no cutoff. Every
|
||||
// surviving date and yesterday (the minimum supported retention) is
|
||||
// safe to keep. Older empty dates cannot be distinguished from deletions.
|
||||
await database.query(`INSERT OR IGNORE INTO CronStatRetention(id,first_day)
|
||||
SELECT 1, MIN(COALESCE(MIN(date),$yesterday),$yesterday) FROM CrontabStats`,
|
||||
{ bind: { yesterday: dayjs().subtract(1,'day').format('YYYY-MM-DD') }, transaction });
|
||||
}
|
||||
await database.query('INSERT INTO SchemaMigrations(id,applied_at) VALUES ($id,CURRENT_TIMESTAMP)',
|
||||
{ bind: { id: retentionId }, transaction });
|
||||
}
|
||||
if (!appliedIds.has(repairId)) {
|
||||
await repairLegacyDailyStatistics(database, transaction, prior);
|
||||
// This reconciliation includes v1 and v2. Record all on fresh installations
|
||||
// so rolling back and upgrading again cannot replay the superseded repair.
|
||||
await database.query(`INSERT OR IGNORE INTO SchemaMigrations(id,applied_at)
|
||||
VALUES ('repair-legacy-daily-statistics-v1',CURRENT_TIMESTAMP),('repair-legacy-daily-statistics-v2',CURRENT_TIMESTAMP),($id,CURRENT_TIMESTAMP)`,
|
||||
{ transaction, bind: { id: repairId } });
|
||||
}
|
||||
|
||||
if (!appliedIds.has(prunedExitMigrationId)) {
|
||||
// Earlier versions could reclaim the last file before upgrading. The
|
||||
// surviving bound booking still identifies the original exit exactly.
|
||||
await database.query(`INSERT OR IGNORE INTO CronUnmatchedBoundExits(trigger_id,outcome,finished_at)
|
||||
SELECT b.trigger_id,b.outcome,b.finished_at FROM CronLegacyExitBookings b
|
||||
WHERE b.bound=1 AND NOT EXISTS (SELECT 1 FROM CronTriggers WHERE id=b.trigger_id)
|
||||
AND NOT EXISTS (SELECT 1 FROM CronBoundExitConflicts WHERE trigger_id=b.trigger_id)`, { transaction });
|
||||
await database.query('INSERT INTO SchemaMigrations(id,applied_at) VALUES ($id,CURRENT_TIMESTAMP)',
|
||||
{ bind: { id: prunedExitMigrationId }, transaction });
|
||||
}
|
||||
|
||||
// Older databases can contain non-JSON values in Envs.labels. Sequelize
|
||||
// parses this column on every environment read, including HTTP startup.
|
||||
await database.query(
|
||||
`UPDATE "Envs" SET "labels" = '[]'
|
||||
WHERE CASE WHEN json_valid("labels")
|
||||
THEN json_type("labels") <> 'array'
|
||||
ELSE 1
|
||||
END`,
|
||||
{ transaction },
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1,9 +1,7 @@
|
||||
import { AuthInfo } from '../data/system';
|
||||
import { App } from '../data/open';
|
||||
import Keyv from 'keyv';
|
||||
import KeyvSqlite from '@keyv/sqlite';
|
||||
import config from '../config';
|
||||
import path from 'path';
|
||||
import { CacheStore } from '../data/cacheStore';
|
||||
|
||||
export enum EKeyv {
|
||||
'apps' = 'apps',
|
||||
@@ -17,8 +15,12 @@ export interface IKeyvStore {
|
||||
lang: string;
|
||||
}
|
||||
|
||||
const keyvSqlite = new KeyvSqlite(path.join(config.dbPath, 'keyv.sqlite'));
|
||||
export const keyvStore = new Keyv<IKeyvStore>({ store: keyvSqlite });
|
||||
const keyvSqlite = new CacheStore();
|
||||
// A stopped database is unavailable, not a cache miss or an expired session.
|
||||
export const keyvStore = new Keyv<IKeyvStore>({
|
||||
store: keyvSqlite,
|
||||
throwOnErrors: true,
|
||||
});
|
||||
|
||||
export const shareStore = {
|
||||
getAuthInfo() {
|
||||
|
||||
@@ -1,320 +0,0 @@
|
||||
import { QueryTypes, Sequelize, Transaction } from 'sequelize';
|
||||
import { blockSize, blockSlots } from './scheduleAudit';
|
||||
|
||||
export type SystemRule = { id: number; schedule: string; name?: string };
|
||||
type Install = {
|
||||
id: number;
|
||||
staged: number;
|
||||
confirmed: number | null;
|
||||
zone: string;
|
||||
rules: string;
|
||||
};
|
||||
type Receipt = {
|
||||
id: string;
|
||||
cron_id: number;
|
||||
system_rule: string | null;
|
||||
observed_at: number;
|
||||
system_dispatch_at: number | null;
|
||||
launched: number;
|
||||
state: string;
|
||||
};
|
||||
|
||||
export async function stageSystemPlan(
|
||||
db: Sequelize,
|
||||
rules: SystemRule[],
|
||||
at = Date.now(),
|
||||
) {
|
||||
const bind = {
|
||||
at,
|
||||
zone: Intl.DateTimeFormat().resolvedOptions().timeZone,
|
||||
rules: JSON.stringify([...rules].sort((a, b) => a.id - b.id)),
|
||||
};
|
||||
return db.transaction(
|
||||
{ type: Transaction.TYPES.IMMEDIATE },
|
||||
async (transaction) => {
|
||||
const [pending] = await db.query<{ id: number }>(
|
||||
`SELECT id FROM (SELECT * FROM CronSystemPlans ORDER BY id DESC LIMIT 1)
|
||||
WHERE confirmed IS NULL AND zone=$zone AND rules=$rules`,
|
||||
{
|
||||
bind: { zone: bind.zone, rules: bind.rules },
|
||||
transaction,
|
||||
type: QueryTypes.SELECT,
|
||||
},
|
||||
);
|
||||
if (pending) return pending.id;
|
||||
const [id] = await db.query(
|
||||
'INSERT INTO CronSystemPlans(staged,zone,rules) VALUES ($at,$zone,$rules)',
|
||||
{ bind, transaction, type: QueryTypes.INSERT },
|
||||
);
|
||||
return id;
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
// On a switch to Node the service can no longer attest the installed daemon rules.
|
||||
export async function suspendSystemPlan(db: Sequelize) {
|
||||
await db.query(
|
||||
`INSERT INTO CronSystemPlans(staged,zone,rules)
|
||||
SELECT $now,zone,'[]' FROM (SELECT zone,confirmed FROM CronSystemPlans ORDER BY id DESC LIMIT 1)
|
||||
WHERE confirmed IS NOT NULL`,
|
||||
{ bind: { now: Date.now() } },
|
||||
);
|
||||
}
|
||||
|
||||
export async function confirmSystemPlan(
|
||||
db: Sequelize,
|
||||
id: number,
|
||||
at = Date.now(),
|
||||
) {
|
||||
await db.transaction(async (transaction) => {
|
||||
await db.query(
|
||||
'UPDATE CronSystemPlans SET confirmed=$at WHERE id=$id AND confirmed IS NULL',
|
||||
{ transaction, bind: { id, at } },
|
||||
);
|
||||
// Keep the effective snapshot preceding the retention window.
|
||||
await db.query(
|
||||
'DELETE FROM CronSystemPlans WHERE id < (SELECT MAX(id) FROM CronSystemPlans WHERE staged < $cutoff AND confirmed IS NOT NULL)',
|
||||
{ transaction, bind: { cutoff: at - 3 * 86400000 } },
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
export async function systemScheduleAudit(
|
||||
db: Sequelize,
|
||||
dayStart: number,
|
||||
now = Date.now(),
|
||||
) {
|
||||
const next = new Date(dayStart);
|
||||
next.setHours(24, 0, 0, 0);
|
||||
const through = Math.min(now - 5000, +next - 1);
|
||||
const { since, installs, receipts } = await db.transaction(
|
||||
{ type: Transaction.TYPES.DEFERRED },
|
||||
async (transaction) => {
|
||||
const [retention] = await db.query<{ since: number }>(
|
||||
'SELECT MAX($dayStart,COALESCE((SELECT cutoff FROM CronHistoryRetention WHERE id=1),0)) AS since',
|
||||
{ transaction, bind: { dayStart }, type: QueryTypes.SELECT },
|
||||
);
|
||||
const since = retention.since;
|
||||
const installs = await db.query<Install>(
|
||||
`SELECT * FROM CronSystemPlans WHERE id >= COALESCE((SELECT MAX(id) FROM CronSystemPlans
|
||||
WHERE confirmed < $since - 60000),0) AND staged <= $now ORDER BY id`,
|
||||
{ transaction, bind: { since, now }, type: QueryTypes.SELECT },
|
||||
);
|
||||
const receipts = await db.query<Receipt>(
|
||||
`SELECT id,cron_id,system_rule,system_dispatch_at,observed_at,state,
|
||||
(command_started_at IS NOT NULL OR script_started_at IS NOT NULL OR
|
||||
(started_at IS NOT NULL AND EXISTS (SELECT 1 FROM CronLegacyExitBookings b
|
||||
WHERE b.trigger_id=CronTriggers.id AND b.bound=1 AND b.disputed=0))) AS launched
|
||||
FROM CronTriggers
|
||||
WHERE source='system' AND COALESCE(system_dispatch_at,observed_at) >= $since
|
||||
AND COALESCE(system_dispatch_at,observed_at) < $end ORDER BY observed_at,id`,
|
||||
{
|
||||
transaction,
|
||||
bind: {
|
||||
since,
|
||||
end: Math.min(
|
||||
+next,
|
||||
Math.floor(through / 60000) * 60000 + 60000,
|
||||
now + 1,
|
||||
),
|
||||
},
|
||||
type: QueryTypes.SELECT,
|
||||
},
|
||||
);
|
||||
return { since, installs, receipts };
|
||||
},
|
||||
);
|
||||
if (!installs.length && !receipts.length) return null;
|
||||
const zone = Intl.DateTimeFormat().resolvedOptions().timeZone;
|
||||
const minute = 60000;
|
||||
const plans = installs.map((plan) => ({
|
||||
...plan,
|
||||
tasks: new Map(
|
||||
(JSON.parse(plan.rules) as SystemRule[]).map((rule) => [rule.id, rule]),
|
||||
),
|
||||
}));
|
||||
const groups = new Map<string, Receipt[]>();
|
||||
const dispatchedTasks = new Set<string>();
|
||||
const legacyThrough = new Map<string, number>();
|
||||
const receiptKey = (task: number, rule: string | null, time: number) =>
|
||||
JSON.stringify([task, rule, time]);
|
||||
for (const row of receipts) {
|
||||
if (row.system_dispatch_at == null || !row.system_rule) {
|
||||
const key = JSON.stringify([row.cron_id, row.system_rule]);
|
||||
legacyThrough.set(
|
||||
key,
|
||||
Math.max(legacyThrough.get(key) ?? 0, row.observed_at),
|
||||
);
|
||||
continue;
|
||||
}
|
||||
dispatchedTasks.add(
|
||||
row.cron_id + '/' + Math.floor(row.system_dispatch_at / minute),
|
||||
);
|
||||
const key = receiptKey(
|
||||
row.cron_id,
|
||||
row.system_rule,
|
||||
Math.floor(row.system_dispatch_at / minute) * minute,
|
||||
);
|
||||
const group = groups.get(key) ?? [];
|
||||
group.push(row);
|
||||
groups.set(key, group);
|
||||
}
|
||||
let expected = 0,
|
||||
observed = 0,
|
||||
dispatched = 0,
|
||||
skipped = 0,
|
||||
missing = 0,
|
||||
duplicates = 0,
|
||||
matchedReceipts = 0;
|
||||
let uncertain = 0,
|
||||
awaiting = 0,
|
||||
switchSlots = 0,
|
||||
partial = false;
|
||||
type Slot = {
|
||||
time: number;
|
||||
task: number;
|
||||
name?: string;
|
||||
status: string;
|
||||
triggerCount: number;
|
||||
startCount: number;
|
||||
skipCount: number;
|
||||
unknownExitCount: number;
|
||||
id?: string;
|
||||
};
|
||||
const recent: Slot[] = [];
|
||||
const dst =
|
||||
new Date(dayStart).getTimezoneOffset() !==
|
||||
new Date(+next - 1).getTimezoneOffset();
|
||||
let baseline = -1,
|
||||
last = -1;
|
||||
const calendar = new Map<string, Set<number>>();
|
||||
for (
|
||||
let time =
|
||||
Math.ceil(Math.max(since, plans[0]?.staged ?? since) / minute) * minute;
|
||||
time <= through;
|
||||
time += minute
|
||||
) {
|
||||
// A successful crontab install acknowledges the file. crond reads changes at
|
||||
// its minute tick. Around that tick either file can still explain a callback.
|
||||
while (last + 1 < plans.length && plans[last + 1].staged <= time + 5000)
|
||||
last++;
|
||||
while (baseline + 1 <= last) {
|
||||
let confirmed = baseline + 1;
|
||||
while (confirmed <= last && plans[confirmed].confirmed == null)
|
||||
confirmed++;
|
||||
if (confirmed > last || plans[confirmed].confirmed! >= time - minute)
|
||||
break;
|
||||
baseline = confirmed;
|
||||
}
|
||||
if (last < 0) continue;
|
||||
const possible = plans.slice(Math.max(0, baseline), last + 1);
|
||||
if (dst || possible.some((plan) => plan.zone !== zone)) {
|
||||
partial = true;
|
||||
continue;
|
||||
}
|
||||
const tasks = new Set<number>();
|
||||
for (const plan of possible)
|
||||
for (const id of plan.tasks.keys()) tasks.add(id);
|
||||
const block = time - (time % blockSize);
|
||||
if (time === block) calendar.clear();
|
||||
const entries: Slot[] = [];
|
||||
for (const task of tasks) {
|
||||
const schedules = new Set<string>();
|
||||
let name: string | undefined;
|
||||
for (const plan of possible) {
|
||||
const rule = plan.tasks.get(task);
|
||||
if (!rule) continue;
|
||||
name = rule.name;
|
||||
let times = calendar.get(rule.schedule);
|
||||
if (!times) {
|
||||
times = new Set(blockSlots(rule.schedule, zone, block));
|
||||
calendar.set(rule.schedule, times);
|
||||
}
|
||||
if (times.has(time)) schedules.add(rule.schedule);
|
||||
}
|
||||
if (!schedules.size) continue;
|
||||
const [schedule] = schedules;
|
||||
const stable =
|
||||
baseline >= 0 &&
|
||||
schedules.size === 1 &&
|
||||
possible.every(
|
||||
(plan) =>
|
||||
plan.confirmed != null &&
|
||||
plan.tasks.get(task)?.schedule === schedule,
|
||||
);
|
||||
const group = [...schedules].flatMap(
|
||||
(rule) => groups.get(receiptKey(task, rule, time)) ?? [],
|
||||
);
|
||||
let status: string;
|
||||
const launched = group.find((row) => row.launched === 1);
|
||||
const skip = group.find((row) => row.state === 'skipped');
|
||||
if (group.length) {
|
||||
++expected;
|
||||
++observed;
|
||||
matchedReceipts += group.length;
|
||||
duplicates += group.length - 1;
|
||||
if (launched) ++dispatched;
|
||||
else if (skip) ++skipped;
|
||||
status = launched ? 'started' : skip ? 'skipped' : 'unconfirmed';
|
||||
} else if (!stable) {
|
||||
++switchSlots;
|
||||
partial = true;
|
||||
status = 'switch';
|
||||
} else {
|
||||
++expected;
|
||||
const lastUndated = Math.max(
|
||||
legacyThrough.get(JSON.stringify([task, null])) ?? 0,
|
||||
legacyThrough.get(JSON.stringify([task, schedule])) ?? 0,
|
||||
);
|
||||
if (
|
||||
time <= lastUndated ||
|
||||
dispatchedTasks.has(task + '/' + time / minute)
|
||||
) {
|
||||
++uncertain;
|
||||
status = 'uncertain';
|
||||
} else if (time + minute > now) {
|
||||
++awaiting;
|
||||
status = 'awaiting';
|
||||
} else {
|
||||
++missing;
|
||||
status = 'missing';
|
||||
}
|
||||
}
|
||||
entries.push({
|
||||
time,
|
||||
task,
|
||||
name,
|
||||
status,
|
||||
triggerCount: group.length,
|
||||
startCount: group.filter((row) => row.launched === 1).length,
|
||||
skipCount: group.filter((row) => row.state === 'skipped').length,
|
||||
unknownExitCount: group.filter((row) => row.launched === 1 && row.state === 'unknown').length,
|
||||
id: (launched || skip || group[0])?.id,
|
||||
});
|
||||
}
|
||||
if (entries.length)
|
||||
recent.unshift(...entries.sort((a, b) => a.task - b.task).slice(0, 25));
|
||||
recent.splice(25);
|
||||
}
|
||||
return {
|
||||
since: Math.max(since, plans[0]?.staged ?? since),
|
||||
through,
|
||||
confirmedAt:
|
||||
[...plans].reverse().find((p) => p.confirmed != null)?.confirmed ?? null,
|
||||
pending: plans.at(-1)?.confirmed == null,
|
||||
partial,
|
||||
expected,
|
||||
observed,
|
||||
dispatched,
|
||||
skipped,
|
||||
missing,
|
||||
duplicates,
|
||||
uncertain,
|
||||
awaiting,
|
||||
switchSlots,
|
||||
actualSkips: receipts.filter((row) => row.state === 'skipped').length,
|
||||
actualStarts: receipts.filter((row) => row.launched === 1).length,
|
||||
unmatched: receipts.length - matchedReceipts,
|
||||
recent,
|
||||
};
|
||||
}
|
||||
@@ -1,79 +0,0 @@
|
||||
import { t } from './i18n';
|
||||
|
||||
// These names control the task runner or the interpreters it starts. Values
|
||||
// managed through the environment API must remain task data, not executable
|
||||
// configuration.
|
||||
const reservedNames = new Set([
|
||||
'TASK_BEFORE',
|
||||
'TASK_AFTER',
|
||||
'WORK_DIR',
|
||||
'TASK_SHELL_PARAMS',
|
||||
'SCRIPT_PARAMS',
|
||||
'WHICH_PROGRAM',
|
||||
'ISJSORPYTHONFILE',
|
||||
'EXPORTED_VARIABLES',
|
||||
'FOUND_DOUBLE_DASH',
|
||||
'LOG_DIR',
|
||||
'LOG_PATH',
|
||||
'ID',
|
||||
'BEGIN_TIMESTAMP',
|
||||
'TIME_FORMAT',
|
||||
'MTIME_FORMAT',
|
||||
'IS_MACOS',
|
||||
'RANDOMDELAY',
|
||||
'RANDOMDELAYFILEEXTENSIONS',
|
||||
'RANDOMDELAYIGNOREDMINUTES',
|
||||
'COMMAND_TIMEOUT_TIME',
|
||||
'SET_U_ON',
|
||||
'_TASK_EXIT_CODE',
|
||||
'PATH',
|
||||
'HOME',
|
||||
'SHELL',
|
||||
'ENV',
|
||||
'BASH_ENV',
|
||||
'BASHOPTS',
|
||||
'SHELLOPTS',
|
||||
'IFS',
|
||||
'CDPATH',
|
||||
'GLOBIGNORE',
|
||||
'PROMPT_COMMAND',
|
||||
'PS4',
|
||||
'NODE_OPTIONS',
|
||||
'NODE_PATH',
|
||||
'PREV_NODE_OPTIONS',
|
||||
'PREV_NODE_PATH',
|
||||
'PREV_PYTHONPATH',
|
||||
'GIT_SSH',
|
||||
'GIT_SSH_COMMAND',
|
||||
'GIT_ASKPASS',
|
||||
'GIT_EXEC_PATH',
|
||||
'GIT_TEMPLATE_DIR',
|
||||
'SSH_ASKPASS',
|
||||
]);
|
||||
|
||||
export function isAllowedTaskEnvName(name: unknown): name is string {
|
||||
if (typeof name !== 'string' || !/^[a-zA-Z_][0-9a-zA-Z_]*$/.test(name)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const upper = name.toUpperCase();
|
||||
return (
|
||||
!reservedNames.has(upper) &&
|
||||
!upper.startsWith('BASH_') &&
|
||||
!upper.startsWith('QL') &&
|
||||
!upper.startsWith('FILE_') &&
|
||||
!upper.startsWith('DIR_') &&
|
||||
!upper.startsWith('LD_') &&
|
||||
!upper.startsWith('DYLD_') &&
|
||||
!upper.startsWith('PYTHON') &&
|
||||
!upper.startsWith('GIT_CONFIG_')
|
||||
);
|
||||
}
|
||||
|
||||
export function assertAllowedTaskEnvName(name: unknown): asserts name is string {
|
||||
if (!isAllowedTaskEnvName(name)) {
|
||||
throw Object.assign(new Error(t('环境变量名称不可使用')), {
|
||||
status: 400,
|
||||
});
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
+12
-31
@@ -2,21 +2,15 @@ import express, { Application, Request } from 'express';
|
||||
import { AuthDataType, SystemModel } from '../data/system';
|
||||
import { normalizeClientIp } from './clientIp';
|
||||
import { t } from './i18n';
|
||||
|
||||
const DEFAULT_TRUST_PROXY = 'loopback';
|
||||
|
||||
type TrustProxyValue = boolean | number | string;
|
||||
|
||||
let activeApp: Application | undefined;
|
||||
|
||||
function getEnvironmentSetting(): string {
|
||||
return process.env.QL_TRUST_PROXY?.trim() || '';
|
||||
}
|
||||
|
||||
function normalizeSetting(value?: string): string {
|
||||
return value?.trim() || DEFAULT_TRUST_PROXY;
|
||||
}
|
||||
|
||||
export function resolveTrustProxy(value?: string): TrustProxyValue {
|
||||
const setting = normalizeSetting(value);
|
||||
if (setting === 'true' || setting === 'false') {
|
||||
@@ -27,7 +21,6 @@ export function resolveTrustProxy(value?: string): TrustProxyValue {
|
||||
}
|
||||
return setting;
|
||||
}
|
||||
|
||||
function validateTrustProxy(value: string): string {
|
||||
const setting = normalizeSetting(value);
|
||||
if (setting.length > 500 || /[\r\n]/.test(setting)) {
|
||||
@@ -36,25 +29,22 @@ function validateTrustProxy(value: string): string {
|
||||
if (/^\d+$/.test(setting) && Number(setting) > 20) {
|
||||
throw new Error(t('代理层数不能超过 20'));
|
||||
}
|
||||
|
||||
const probe = express();
|
||||
probe.set('trust proxy', resolveTrustProxy(setting));
|
||||
return setting;
|
||||
}
|
||||
|
||||
async function getStoredSetting(): Promise<string> {
|
||||
const doc = await SystemModel.findOne({
|
||||
where: { type: AuthDataType.systemConfig },
|
||||
});
|
||||
const info = (doc?.get('info') || {}) as Record<string, unknown>;
|
||||
const doc = await SystemModel.findOne(
|
||||
{ type: AuthDataType.systemConfig },
|
||||
{},
|
||||
);
|
||||
const info = (doc?.info || {}) as Record<string, unknown>;
|
||||
return typeof info.trustProxy === 'string' ? info.trustProxy : '';
|
||||
}
|
||||
|
||||
export async function getTrustProxyConfig() {
|
||||
const environmentSetting = getEnvironmentSetting();
|
||||
const storedSetting = await getStoredSetting();
|
||||
const trustProxy = normalizeSetting(environmentSetting || storedSetting);
|
||||
|
||||
return {
|
||||
trustProxy,
|
||||
source: environmentSetting
|
||||
@@ -65,36 +55,31 @@ export async function getTrustProxyConfig() {
|
||||
editable: !environmentSetting,
|
||||
};
|
||||
}
|
||||
|
||||
export async function initializeTrustProxy(app: Application) {
|
||||
activeApp = app;
|
||||
const { trustProxy } = await getTrustProxyConfig();
|
||||
app.set('trust proxy', resolveTrustProxy(trustProxy));
|
||||
}
|
||||
|
||||
export async function updateTrustProxy(value: string) {
|
||||
if (getEnvironmentSetting()) {
|
||||
throw new Error(t('环境变量 QL_TRUST_PROXY 已生效,系统设置不可覆盖'));
|
||||
}
|
||||
|
||||
const trustProxy = validateTrustProxy(value);
|
||||
const doc = await SystemModel.findOne({
|
||||
where: { type: AuthDataType.systemConfig },
|
||||
});
|
||||
const doc = await SystemModel.findOne(
|
||||
{ type: AuthDataType.systemConfig },
|
||||
{},
|
||||
);
|
||||
if (!doc) {
|
||||
throw new Error(t('系统配置不存在'));
|
||||
}
|
||||
|
||||
const plain = doc.get({ plain: true });
|
||||
await SystemModel.update(
|
||||
const plain = doc;
|
||||
await SystemModel.nativeUpdate(
|
||||
{ id: plain.id },
|
||||
{ info: { ...(plain.info || {}), trustProxy } as any },
|
||||
{ where: { id: plain.id } },
|
||||
);
|
||||
activeApp?.set('trust proxy', resolveTrustProxy(trustProxy));
|
||||
|
||||
return getTrustProxyConfig();
|
||||
}
|
||||
|
||||
function parseForwardedFor(value: string | string[] | undefined): string[] {
|
||||
const values = Array.isArray(value) ? value : value ? [value] : [];
|
||||
return values
|
||||
@@ -102,7 +87,6 @@ function parseForwardedFor(value: string | string[] | undefined): string[] {
|
||||
.map((item) => normalizeClientIp(item))
|
||||
.filter(Boolean);
|
||||
}
|
||||
|
||||
export async function diagnoseClientIp(req: Request) {
|
||||
const remoteAddress = normalizeClientIp(req.socket.remoteAddress);
|
||||
const forwardedFor = parseForwardedFor(req.headers['x-forwarded-for']);
|
||||
@@ -112,7 +96,6 @@ export async function diagnoseClientIp(req: Request) {
|
||||
const trust = req.app.get('trust proxy fn') as
|
||||
| ((ip: string, hop: number) => boolean)
|
||||
| undefined;
|
||||
|
||||
let selectedIndex = Math.max(hopsFromApp.length - 1, 0);
|
||||
for (let index = 0; index < hopsFromApp.length - 1; index += 1) {
|
||||
if (!trust?.(hopsFromApp[index], index)) {
|
||||
@@ -120,7 +103,6 @@ export async function diagnoseClientIp(req: Request) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
const hops = hopsFromApp.map((ip, index) => ({
|
||||
ip,
|
||||
hop: index,
|
||||
@@ -131,7 +113,6 @@ export async function diagnoseClientIp(req: Request) {
|
||||
? 'client'
|
||||
: 'not_checked',
|
||||
}));
|
||||
|
||||
return {
|
||||
...(await getTrustProxyConfig()),
|
||||
remoteAddress,
|
||||
|
||||
+1
-1
@@ -23,5 +23,5 @@
|
||||
"esModuleInterop": true
|
||||
},
|
||||
"include": ["./**/*"],
|
||||
"exclude": ["node_modules"]
|
||||
"exclude": ["node_modules", "./data/databaseWorker.ts"]
|
||||
}
|
||||
|
||||
@@ -70,10 +70,14 @@ export const commonCronSchema = {
|
||||
}
|
||||
|
||||
// For other absolute paths, ensure they are within the safe log directory
|
||||
const relative = path.relative(config.logPath, value);
|
||||
if (!relative || relative === '..' || relative.startsWith('..' + path.sep) || path.isAbsolute(relative)) {
|
||||
const normalizedValue = path.normalize(value);
|
||||
const normalizedLogPath = path.normalize(config.logPath);
|
||||
|
||||
if (!normalizedValue.startsWith(normalizedLogPath)) {
|
||||
return helpers.error('string.unsafePath');
|
||||
}
|
||||
|
||||
return value;
|
||||
}
|
||||
|
||||
if (
|
||||
@@ -93,9 +97,6 @@ export const commonCronSchema = {
|
||||
'string.max': '日志名称不能超过100个字符',
|
||||
'string.unsafePath': '绝对路径必须在日志目录内或使用 /dev/null',
|
||||
}),
|
||||
skip_if_pending: Joi.boolean().optional().allow(null),
|
||||
max_queue_wait: Joi.number().integer().min(0).max(86400).allow(null),
|
||||
catchup_seconds: Joi.number().integer().min(0).max(86400).allow(null),
|
||||
allow_multiple_instances: Joi.number().optional().valid(0, 1).allow(null),
|
||||
work_dir: Joi.string().optional().allow('').allow(null),
|
||||
};
|
||||
|
||||
+1
-1
@@ -38,7 +38,7 @@ check installs dependencies, repairs and reloads; inspect its before/after obser
|
||||
|
||||
On a panel containing the selection loader, set `QL_CLI_ROOT=/absolute/path/to/built/cli` to the internal build directory containing the full dist tree, **not an npm installation**. Restart to create private ~/bin ql/task/cron wrappers and prioritize them for panel processes. Independent terminals should use the selected absolute path. Unset the variable and restart to restore Shell entries. Invalid paths report errors without silent fallback. Original Shell entries remain the default.
|
||||
|
||||
dist/startup.js retains startup/reload compatibility; dist/compat.js and dist/subscription-worker.js are internal adapters, not npm commands. The CLI negotiates receipt fields with the running panel. Set `QL_CLI_LIFECYCLE=legacy` to force the legacy format.
|
||||
dist/startup.js retains startup/reload compatibility; dist/compat.js and dist/subscription-worker.js are internal adapters, not npm commands. Lifecycle fields follow the installed panel version; customized versions may select QL_CLI_LIFECYCLE=legacy|extended.
|
||||
|
||||
The separate [qinglong-local skill](skills/qinglong-local/SKILL.md) covers execution and maintenance. Use qinglong-cli for remote API management. QL_LANG=en selects English help/messages while JSON fields remain stable.
|
||||
|
||||
|
||||
+1
-1
@@ -40,7 +40,7 @@ repo/raw 沿用位置参数,使用 QL_DIR/QL_DATA_DIR,不接受 --root/--jso
|
||||
|
||||
包含选择加载器的面板设置 `QL_CLI_ROOT=/absolute/path/to/built/cli`,指向包含完整 dist 的面板工具构建目录,**不能指向 npm 包**。重启后加载器在 ~/bin 创建私有 ql/task/cron 包装器,并为面板进程优先使用它们;独立终端应显式使用该路径。清除变量并重启恢复原 Shell 入口。无效路径报错,不静默降级。默认仍保留旧 Shell 入口。
|
||||
|
||||
`dist/startup.js` 兼容旧启动/reload;`dist/compat.js` 与 `dist/subscription-worker.js` 保留内部适配用途,不注册为 npm 命令。CLI 根据运行中的面板对回执字段的校验结果选择协议。设置 `QL_CLI_LIFECYCLE=legacy` 可强制使用旧格式。
|
||||
`dist/startup.js` 兼容旧启动/reload;`dist/compat.js` 与 `dist/subscription-worker.js` 保留内部适配用途,不注册为 npm 命令。生命周期根据已安装面板版本选择字段,定制版本可设置 QL_CLI_LIFECYCLE=legacy|extended。
|
||||
|
||||
独立 Skill 位于 [skills/qinglong-local](skills/qinglong-local/SKILL.md),包含完整执行与维护参考。远程管理另用 qinglong-cli Skill。`QL_LANG=en` 切换帮助和执行提示;JSON 字段保持一致。
|
||||
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user