Files
zhguchiy_perchik/migrations/0001_init.sql
T
omar 4499a6ee37
CI / validate (push) Successful in 38s
CI / gateway-contract (push) Successful in 2m1s
CI / images (deploy/Dockerfile.web, web) (push) Successful in 50s
CI / images (deploy/Dockerfile.checker, checker) (push) Successful in 1m4s
CI / images (deploy/Dockerfile.api, api) (push) Successful in 1m14s
CI / images (deploy/Dockerfile.http-gateway, http-gateway) (push) Successful in 1m11s
Add authenticated SOCKS5 exports and a live public web switch
Use the same pinned upstream, node credentials and routing restrictions for both proxy listeners.
Apply the admin-selected destination policy on each new request and verify exports with independent proxy clients.
2026-11-27 06:43:27 +03:00

276 lines
13 KiB
PL/PgSQL

-- zhguchiy_perchik schema. Applied idempotently by the checker on boot.
-- Model: "only working / last completed session". The panel and subscriptions
-- always read the single check_sessions row with is_current = true.
-- ---------------------------------------------------------------------------
-- settings: typed key/value config editable from the panel.
-- ---------------------------------------------------------------------------
CREATE TABLE IF NOT EXISTS settings (
key text PRIMARY KEY,
value text NOT NULL,
updated_at timestamptz NOT NULL DEFAULT now()
);
-- ---------------------------------------------------------------------------
-- sources: proxy source lists (txt / subscription URLs).
-- ---------------------------------------------------------------------------
CREATE TABLE IF NOT EXISTS sources (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
name text NOT NULL,
url text NOT NULL UNIQUE,
kind text NOT NULL DEFAULT 'auto', -- auto | plain | base64
enabled boolean NOT NULL DEFAULT true,
last_fetched_at timestamptz,
last_line_count integer NOT NULL DEFAULT 0,
last_error text NOT NULL DEFAULT '',
created_at timestamptz NOT NULL DEFAULT now()
);
ALTER TABLE sources ADD COLUMN IF NOT EXISTS kind text NOT NULL DEFAULT 'auto';
-- ---------------------------------------------------------------------------
-- proxies: persistent per-canonical-URL history. Kept even while a proxy is
-- currently invalid. Never served directly — only working ones from the
-- current session are. Source is pinned first-seen.
-- ---------------------------------------------------------------------------
CREATE TABLE IF NOT EXISTS proxies (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
canonical_url text NOT NULL UNIQUE,
protocol text NOT NULL,
host text NOT NULL,
port integer NOT NULL,
source_id bigint REFERENCES sources(id) ON DELETE SET NULL,
source_name text NOT NULL DEFAULT '',
first_seen timestamptz NOT NULL DEFAULT now(),
last_alive timestamptz,
consecutive_failures integer NOT NULL DEFAULT 0,
total_checks bigint NOT NULL DEFAULT 0,
total_passes bigint NOT NULL DEFAULT 0,
last_latency_ms integer NOT NULL DEFAULT 0,
last_speed_mbps double precision NOT NULL DEFAULT 0,
last_country text NOT NULL DEFAULT '',
last_exit_ip text NOT NULL DEFAULT '',
updated_at timestamptz NOT NULL DEFAULT now()
);
CREATE INDEX IF NOT EXISTS idx_proxies_protocol ON proxies (protocol);
CREATE INDEX IF NOT EXISTS idx_proxies_last_country ON proxies (last_country);
-- ---------------------------------------------------------------------------
-- check_sessions: one per check cycle. Kept forever (trends). Exactly one row
-- has is_current = true (enforced by the partial unique index below).
-- ---------------------------------------------------------------------------
CREATE TABLE IF NOT EXISTS check_sessions (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
status text NOT NULL DEFAULT 'running', -- running|completed|cancelled|failed
trigger_kind text NOT NULL DEFAULT 'scheduled', -- scheduled|manual
is_current boolean NOT NULL DEFAULT false,
cancel_requested boolean NOT NULL DEFAULT false,
started_at timestamptz NOT NULL DEFAULT now(),
finished_at timestamptz,
duration_ms bigint NOT NULL DEFAULT 0,
total_raw_lines integer NOT NULL DEFAULT 0,
unique_candidates integer NOT NULL DEFAULT 0,
collapsed integer NOT NULL DEFAULT 0, -- raw - unique (dedup/junk count)
progress_total integer NOT NULL DEFAULT 0,
progress_done integer NOT NULL DEFAULT 0,
valid integer NOT NULL DEFAULT 0,
invalid integer NOT NULL DEFAULT 0,
error text NOT NULL DEFAULT ''
);
-- exactly one current session
CREATE UNIQUE INDEX IF NOT EXISTS uniq_current_session
ON check_sessions (is_current) WHERE is_current;
CREATE INDEX IF NOT EXISTS idx_sessions_status_finished
ON check_sessions (status, finished_at DESC);
-- ---------------------------------------------------------------------------
-- session_proxies: working proxies of a session with metrics at that session.
-- Denormalized so subscription/proxy-list serving is a single filtered scan.
-- ---------------------------------------------------------------------------
CREATE TABLE IF NOT EXISTS session_proxies (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
session_id bigint NOT NULL REFERENCES check_sessions(id) ON DELETE CASCADE,
proxy_id bigint NOT NULL REFERENCES proxies(id) ON DELETE CASCADE,
canonical_url text NOT NULL,
protocol text NOT NULL,
host text NOT NULL,
port integer NOT NULL,
source_name text NOT NULL DEFAULT '',
latency_ms integer NOT NULL DEFAULT 0,
speed_mbps double precision NOT NULL DEFAULT 0,
country text NOT NULL DEFAULT '',
exit_ip text NOT NULL DEFAULT '',
is_new boolean NOT NULL DEFAULT false,
UNIQUE (session_id, proxy_id)
);
CREATE INDEX IF NOT EXISTS idx_sp_session ON session_proxies (session_id);
CREATE INDEX IF NOT EXISTS idx_sp_session_protocol ON session_proxies (session_id, protocol);
CREATE INDEX IF NOT EXISTS idx_sp_session_country ON session_proxies (session_id, country);
CREATE INDEX IF NOT EXISTS idx_sp_session_exitip ON session_proxies (session_id, exit_ip);
-- ---------------------------------------------------------------------------
-- Compact per-session aggregate stats (protocol / source breakdown incl. valid%).
-- We do NOT store every failed candidate — only these counters.
-- ---------------------------------------------------------------------------
CREATE TABLE IF NOT EXISTS session_protocol_stats (
session_id bigint NOT NULL REFERENCES check_sessions(id) ON DELETE CASCADE,
protocol text NOT NULL,
checked integer NOT NULL DEFAULT 0,
passed integer NOT NULL DEFAULT 0,
failed integer NOT NULL DEFAULT 0,
PRIMARY KEY (session_id, protocol)
);
CREATE TABLE IF NOT EXISTS session_source_stats (
session_id bigint NOT NULL REFERENCES check_sessions(id) ON DELETE CASCADE,
source_name text NOT NULL,
raw_lines integer NOT NULL DEFAULT 0,
unique_candidates integer NOT NULL DEFAULT 0,
passed integer NOT NULL DEFAULT 0,
PRIMARY KEY (session_id, source_name)
);
-- ---------------------------------------------------------------------------
-- subscriptions: client sub-links with filters, format, unique_ips, sort, ttl.
-- ---------------------------------------------------------------------------
CREATE TABLE IF NOT EXISTS subscriptions (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
token text NOT NULL UNIQUE,
name text NOT NULL DEFAULT '',
enabled boolean NOT NULL DEFAULT true,
format text NOT NULL DEFAULT 'plain', -- plain|base64|clash|singbox
filter_protocols text[] NOT NULL DEFAULT '{}',
filter_countries text[] NOT NULL DEFAULT '{}',
filter_sources text[] NOT NULL DEFAULT '{}',
url_search text[] NOT NULL DEFAULT '{}', -- proxy_url substrings (match ANY)
max_latency_ms integer,
min_speed_mbps double precision,
limit_n integer,
unique_ips boolean NOT NULL DEFAULT false,
unique_ips_metric text NOT NULL DEFAULT 'speed', -- speed|latency
sort_by text[] NOT NULL DEFAULT '{}', -- e.g. {speed:desc,latency:asc}
expires_at timestamptz,
request_count bigint NOT NULL DEFAULT 0,
last_requested_at timestamptz,
created_at timestamptz NOT NULL DEFAULT now()
);
ALTER TABLE subscriptions ADD COLUMN IF NOT EXISTS url_search text[] NOT NULL DEFAULT '{}';
-- ---------------------------------------------------------------------------
-- Default settings (only inserted when missing).
-- ---------------------------------------------------------------------------
INSERT INTO settings (key, value) VALUES
('check_interval_hours', '12'),
('workers', '10'),
('timeout_sec', '5'),
('max_latency_ms', '1000'),
('min_speed_mbps', '3'),
('speedtest_enabled', 'true'),
('speedtest_url', 'https://speedtest.selectel.ru/10MB'),
('geoip_db_url', 'https://cdn.jsdelivr.net/npm/@ip-location-db/geolite2-geo-whois-asn-country-mmdb/geolite2-geo-whois-asn-country.mmdb'),
('auto_enabled', 'true'),
('telegram_bot_token', ''),
('telegram_chat_id', ''),
('telegram_notify_start', 'false'),
('telegram_notify_finish', 'true')
ON CONFLICT (key) DO NOTHING;
-- Replace the old built-in HTTP URL without changing custom settings.
UPDATE settings SET value = 'https://speedtest.selectel.ru/10MB', updated_at = now()
WHERE key = 'speedtest_url' AND value = 'http://cachefly.cachefly.net/10mb.test';
-- ---------------------------------------------------------------------------
-- HTTP gateway: the checker owns the published snapshot, the gateway owns
-- only its runtime and health. The views expose no historical rows or unrelated settings.
-- ---------------------------------------------------------------------------
INSERT INTO settings (key, value) VALUES
('gateway_check_interval_minutes', '20'),
('gateway_allow_all_sites', 'false')
ON CONFLICT (key) DO NOTHING;
CREATE OR REPLACE VIEW gateway_current_session WITH (security_barrier = true) AS
SELECT id AS session_id, finished_at AS session_finished_at
FROM check_sessions
WHERE is_current AND status = 'completed';
CREATE OR REPLACE VIEW gateway_candidates WITH (security_barrier = true) AS
SELECT cs.id AS session_id, cs.finished_at AS session_finished_at,
sp.id AS membership_id, sp.proxy_id, sp.canonical_url, sp.protocol,
sp.country, sp.exit_ip, sp.speed_mbps,
COALESCE((SELECT value COLLATE "C" = 'true' FROM settings
WHERE key = 'gateway_allow_all_sites'), false) AS allow_all_sites
FROM check_sessions cs
JOIN session_proxies sp ON sp.session_id = cs.id
WHERE cs.is_current AND cs.status = 'completed';
CREATE OR REPLACE VIEW gateway_check_interval WITH (security_barrier = true) AS
SELECT value FROM settings WHERE key = 'gateway_check_interval_minutes';
CREATE TABLE IF NOT EXISTS gateway_node_health (
proxy_id bigint PRIMARY KEY REFERENCES proxies(id) ON DELETE CASCADE,
tested_membership_id bigint NOT NULL,
ok boolean NOT NULL,
checked_at timestamptz NOT NULL,
latency_ms integer,
CHECK ((ok AND latency_ms IS NOT NULL AND latency_ms >= 0)
OR (NOT ok AND latency_ms IS NULL))
);
CREATE TABLE IF NOT EXISTS gateway_runtime (
id integer PRIMARY KEY CHECK (id = 1),
store_uuid uuid NOT NULL DEFAULT gen_random_uuid(),
heartbeat_at timestamptz,
last_started_at timestamptz,
last_attempt_finished_at timestamptz,
last_success_at timestamptz,
next_full_at timestamptz,
phase text NOT NULL DEFAULT 'idle' CHECK (phase IN ('idle', 'checking', 'degraded')),
last_error_code text CHECK (last_error_code IN ('config', 'control', 'database', 'probe', 'interrupted'))
);
INSERT INTO gateway_runtime (id) VALUES (1) ON CONFLICT (id) DO NOTHING;
-- Publication takes short-lived locks without granting the gateway access to
-- the checker tables. Bind their schema here; never use the caller's search_path.
DO $gateway_ddl$
BEGIN
EXECUTE format($definition$
CREATE OR REPLACE FUNCTION %1$I.gateway_lock_current(expected_session_id bigint)
RETURNS boolean
LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, pg_temp
AS $body$
BEGIN
IF expected_session_id IS NULL THEN
-- Before the first publication there is no row to lock.
LOCK TABLE %1$I.check_sessions IN SHARE MODE;
RETURN NOT EXISTS (
SELECT 1 FROM %1$I.check_sessions
WHERE is_current AND status = 'completed'
);
END IF;
PERFORM 1 FROM %1$I.check_sessions
WHERE id = expected_session_id AND is_current AND status = 'completed'
FOR SHARE;
RETURN FOUND;
END;
$body$
$definition$, current_schema());
EXECUTE format($definition$
CREATE OR REPLACE FUNCTION %1$I.gateway_lock_memberships(expected_session_id bigint, memberships bigint[])
RETURNS TABLE(proxy_id bigint, membership_id bigint)
LANGUAGE sql SECURITY DEFINER SET search_path = pg_catalog, pg_temp
AS $body$
SELECT sp.proxy_id, sp.id
FROM %1$I.check_sessions cs
JOIN %1$I.session_proxies sp ON sp.session_id = cs.id
WHERE cs.id = expected_session_id AND cs.is_current AND cs.status = 'completed'
AND sp.id = ANY(memberships)
FOR SHARE OF cs FOR KEY SHARE OF sp;
$body$
$definition$, current_schema());
END;
$gateway_ddl$;
REVOKE EXECUTE ON FUNCTION gateway_lock_current(bigint), gateway_lock_memberships(bigint, bigint[]) FROM PUBLIC;