Add independent MIT account-rate500 policy source supplement
This commit is contained in:
@@ -0,0 +1,282 @@
|
||||
"""Opt-in v2 primary allocator with bounded replay state and explicit leases.
|
||||
|
||||
Credit issuance is not proof of deployed enforcement. At rate R and bucket B,
|
||||
issuance during T is bounded by B+R*T. Pre-issued credit has TTL <= 1 second;
|
||||
gate admission can therefore have an extra B+R*TTL release allowance, not an
|
||||
instantaneous strict configured-rate wire guarantee. Kernel/transport buffering is
|
||||
outside this account payload contract. Unused credits are burned, not refunded.
|
||||
|
||||
One durable node epoch fences restarted executors. One persisted response and
|
||||
sequence high-water per node/subscription/direction replaces a per-RPC ledger.
|
||||
Do not delete/reset same-epoch lane state, or reset node epochs. UUID request_id
|
||||
is correlation; the replay identity is (node, epoch, lane, sequence). Same seq
|
||||
retries retain their first monotonic request-start deadline at the executor.
|
||||
"""
|
||||
import hashlib
|
||||
import json
|
||||
import uuid
|
||||
from datetime import timedelta
|
||||
|
||||
from django.conf import settings
|
||||
from django.contrib.auth import get_user_model
|
||||
from django.db import DatabaseError, IntegrityError, connections, transaction
|
||||
from django.http import JsonResponse
|
||||
from django.views.decorators.csrf import csrf_exempt
|
||||
from django.views.decorators.http import require_http_methods
|
||||
|
||||
from .models import ACCOUNT_BANDWIDTH_EXCEPTION_KEY, AccountBandwidthExemption, AccountBandwidthPolicy
|
||||
from .policy import _limit_in_bytes
|
||||
from .helpers import (
|
||||
BURST_MS, DB, MAX_REQUEST_BYTES, MICRO, BudgetRejected, _database_now,
|
||||
_node_allowed, _require_primary_backend, _unique_json_pairs,
|
||||
)
|
||||
from .models import AccountBandwidthBucket, AccountBandwidthExecutor, AccountBandwidthLane
|
||||
from control.models import Node, Subscription
|
||||
|
||||
CONTRACT = 2
|
||||
POLICY_VERSION = "shared-account-budget-v2"
|
||||
MAX_SEQUENCE = 2**63 - 1
|
||||
MAX_TTL_MS = 1000
|
||||
MAX_RESPONSE_BYTES = 2048
|
||||
|
||||
|
||||
def _reply(payload, status=200):
|
||||
response = JsonResponse(payload, status=status)
|
||||
response["Cache-Control"] = "no-store"
|
||||
return response
|
||||
|
||||
|
||||
def _integer(value, minimum, maximum=MAX_SEQUENCE):
|
||||
return type(value) is int and minimum <= value <= maximum
|
||||
|
||||
|
||||
def _uuid(value):
|
||||
return (isinstance(value, str) and len(value) == 36 and str(uuid.UUID(value)) == value
|
||||
and uuid.UUID(value).int != 0)
|
||||
|
||||
|
||||
def _contract(payload, fields):
|
||||
if (not isinstance(payload, dict) or set(payload) != fields
|
||||
or type(payload["contract"]) is not int or payload["contract"] != CONTRACT
|
||||
or payload["policy_version"] != POLICY_VERSION):
|
||||
raise ValueError("unsupported budget v2 contract")
|
||||
|
||||
|
||||
def _parse_open(payload):
|
||||
_contract(payload, {"contract", "policy_version", "expected_epoch", "boot_id", "registration_id"})
|
||||
if not _integer(payload["expected_epoch"], 0) or not all(_uuid(payload[key]) for key in ("boot_id", "registration_id")):
|
||||
raise ValueError("invalid executor registration")
|
||||
return payload
|
||||
|
||||
|
||||
def _parse_credit(payload):
|
||||
_contract(payload, {"contract", "policy_version", "subscription_id", "credential_uuid", "direction",
|
||||
"requested_bytes", "request_id", "boot_id", "session_id", "ttl_ms", "executor_epoch", "sequence"})
|
||||
if (not all(_integer(payload[key], 1) for key in ("subscription_id", "executor_epoch", "sequence"))
|
||||
or not _integer(payload["requested_bytes"], 1, MAX_REQUEST_BYTES)
|
||||
or not _integer(payload["ttl_ms"], 50, MAX_TTL_MS)
|
||||
or payload["direction"] not in ("upload", "download")
|
||||
or not all(_uuid(payload[key]) for key in ("credential_uuid", "request_id", "boot_id", "session_id"))):
|
||||
raise ValueError("invalid budget v2 request")
|
||||
return payload
|
||||
|
||||
|
||||
def _timeouts():
|
||||
if connections[DB].vendor == "postgresql":
|
||||
with connections[DB].cursor() as cursor:
|
||||
cursor.execute("SET LOCAL lock_timeout = '100ms'")
|
||||
cursor.execute("SET LOCAL statement_timeout = '250ms'")
|
||||
|
||||
|
||||
def _current_node(node, lock=False):
|
||||
query = Node.objects.using(DB)
|
||||
if lock:
|
||||
query = query.select_for_update(nowait=True)
|
||||
current = query.filter(pk=node.pk).first()
|
||||
if not _node_allowed(current) or current.agent_token_digest != node.agent_token_digest:
|
||||
raise BudgetRejected("node_not_authorized", 401)
|
||||
return current
|
||||
|
||||
|
||||
def _check_clock(now, *floors):
|
||||
if any(floor is not None and now < floor for floor in floors):
|
||||
raise BudgetRejected("budget_clock_regressed", 503)
|
||||
|
||||
|
||||
def read_executor(node):
|
||||
_require_primary_backend()
|
||||
current = _current_node(node)
|
||||
state = AccountBandwidthExecutor.objects.using(DB).filter(node=current).first()
|
||||
_check_clock(_database_now(), state.clock_floor if state else None)
|
||||
return {"contract": CONTRACT, "policy_version": POLICY_VERSION, "node_slug": current.slug,
|
||||
"executor_epoch": state.epoch if state else 0}
|
||||
|
||||
|
||||
def _registration_response(state, node):
|
||||
return {"contract": CONTRACT, "policy_version": POLICY_VERSION, "node_slug": node.slug,
|
||||
"executor_epoch": state.epoch, "boot_id": str(state.boot_id), "registration_id": str(state.registration_id)}
|
||||
|
||||
|
||||
def open_executor(node, payload):
|
||||
payload = _parse_open(payload)
|
||||
_require_primary_backend()
|
||||
with transaction.atomic(using=DB):
|
||||
_timeouts()
|
||||
current = _current_node(node, lock=True)
|
||||
state = AccountBandwidthExecutor.objects.using(DB).filter(node=current).first()
|
||||
now = _database_now()
|
||||
_check_clock(now, state.clock_floor if state else None)
|
||||
if state:
|
||||
same_registration = (str(state.boot_id) == payload["boot_id"] and str(state.registration_id) == payload["registration_id"])
|
||||
if same_registration and payload["expected_epoch"] == state.epoch - 1:
|
||||
return _registration_response(state, current)
|
||||
if (payload["expected_epoch"] != state.epoch or state.epoch == MAX_SEQUENCE
|
||||
or str(state.boot_id) == payload["boot_id"] or str(state.registration_id) == payload["registration_id"]):
|
||||
raise BudgetRejected("fenced", 409)
|
||||
state.epoch += 1
|
||||
state.boot_id, state.registration_id = payload["boot_id"], payload["registration_id"]
|
||||
state.opened_at = state.clock_floor = now
|
||||
state.save(using=DB)
|
||||
else:
|
||||
if payload["expected_epoch"] != 0:
|
||||
raise BudgetRejected("fenced", 409)
|
||||
state = AccountBandwidthExecutor.objects.using(DB).create(node=current, epoch=1,
|
||||
boot_id=payload["boot_id"], registration_id=payload["registration_id"], opened_at=now, clock_floor=now)
|
||||
return _registration_response(state, current)
|
||||
|
||||
|
||||
def _authorize_subscription(node, payload):
|
||||
owner_id = Subscription.objects.using(DB).filter(pk=payload["subscription_id"]).values_list("user_id", flat=True).first()
|
||||
if owner_id is None:
|
||||
raise BudgetRejected("subscription_not_authorized")
|
||||
user = get_user_model().objects.using(DB).select_for_update().filter(pk=owner_id).first()
|
||||
subscription = Subscription.objects.using(DB).select_for_update(of=("self",)).select_related("plan").filter(pk=payload["subscription_id"]).first()
|
||||
if user is None or subscription is None or subscription.user_id != user.pk:
|
||||
raise BudgetRejected("subscription_not_authorized")
|
||||
# Same lock order as v1: account/subscription first, node NOWAIT afterwards.
|
||||
current = _current_node(node, lock=True)
|
||||
state = AccountBandwidthExecutor.objects.using(DB).filter(node=current).first()
|
||||
if state is None or state.epoch != payload["executor_epoch"] or str(state.boot_id) != payload["boot_id"]:
|
||||
raise BudgetRejected("fenced", 409)
|
||||
now = _database_now()
|
||||
_check_clock(now, state.clock_floor)
|
||||
subscription.user = user
|
||||
if (not user.service_enabled or subscription.status != Subscription.Status.ACTIVE
|
||||
or subscription.provisioning_state != Subscription.ProvisioningState.ACTIVE
|
||||
or str(subscription.credential_uuid) != payload["credential_uuid"]
|
||||
or subscription.route_mode not in Subscription.RouteMode.values or subscription.online_payment_pending
|
||||
or (subscription.starts_at and subscription.starts_at > now)
|
||||
or (subscription.expires_at and subscription.expires_at <= now)
|
||||
or (subscription.traffic_limit_bytes and subscription.used_bytes >= subscription.traffic_limit_bytes)
|
||||
or not subscription.nodes_for_subscription().using(DB).filter(pk=current.pk).exists()):
|
||||
raise BudgetRejected("subscription_not_authorized")
|
||||
return user, subscription, current, state, now
|
||||
|
||||
|
||||
def issue_credit_v2(node, payload):
|
||||
payload = _parse_credit(payload)
|
||||
_require_primary_backend()
|
||||
fingerprint = hashlib.sha256(json.dumps({"node_id": node.pk, **payload}, sort_keys=True, separators=(",", ":")).encode()).hexdigest()
|
||||
with transaction.atomic(using=DB):
|
||||
_timeouts()
|
||||
user, subscription, current, executor, now = _authorize_subscription(node, payload)
|
||||
lane = AccountBandwidthLane.objects.using(DB).filter(node=current, subscription=subscription, direction=payload["direction"]).first()
|
||||
same_epoch = lane is not None and lane.executor_epoch == executor.epoch
|
||||
if same_epoch:
|
||||
if str(lane.session_id) != payload["session_id"] or str(lane.credential_uuid) != payload["credential_uuid"] or lane.user_id != user.pk:
|
||||
raise BudgetRejected("fenced", 409)
|
||||
_check_clock(now, lane.issued_at)
|
||||
if payload["sequence"] == lane.sequence:
|
||||
if fingerprint != lane.fingerprint:
|
||||
raise BudgetRejected("sequence_conflict", 409)
|
||||
return json.loads(lane.response)
|
||||
if payload["sequence"] != lane.sequence + 1:
|
||||
raise BudgetRejected("sequence_out_of_order", 409)
|
||||
elif payload["sequence"] != 1:
|
||||
raise BudgetRejected("sequence_out_of_order", 409)
|
||||
if lane is not None and lane.executor_epoch > executor.epoch:
|
||||
raise BudgetRejected("fenced", 409)
|
||||
# The stable User row is already locked: serialize policy creation and all lanes.
|
||||
policy, _ = AccountBandwidthPolicy.objects.using(DB).get_or_create(user=user)
|
||||
rate = _limit_in_bytes(getattr(policy, payload["direction"] + "_limit_kib_per_second"))
|
||||
exempt = AccountBandwidthExemption.objects.using(DB).filter(policy_key=ACCOUNT_BANDWIDTH_EXCEPTION_KEY, user_id=user.pk).exists()
|
||||
capacity = rate * BURST_MS * 1000
|
||||
bucket, _ = AccountBandwidthBucket.objects.using(DB).get_or_create(user=user, direction=payload["direction"],
|
||||
defaults={"available_microbytes": 0 if exempt else capacity, "rate_bytes_per_second": rate, "exempt": exempt, "refilled_at": now})
|
||||
_check_clock(now, bucket.refilled_at)
|
||||
if bucket.rate_bytes_per_second != rate or bucket.exempt != exempt:
|
||||
available = 0
|
||||
else:
|
||||
elapsed = now - bucket.refilled_at
|
||||
elapsed_us = (elapsed.days * 86400 + elapsed.seconds) * MICRO + elapsed.microseconds
|
||||
available = min(capacity, bucket.available_microbytes + elapsed_us * rate)
|
||||
granted = 0 if exempt else min(payload["requested_bytes"], available // MICRO)
|
||||
bucket.available_microbytes = 0 if exempt else available - granted * MICRO
|
||||
bucket.rate_bytes_per_second, bucket.exempt, bucket.refilled_at = rate, exempt, now
|
||||
bucket.save(using=DB)
|
||||
expiry = now + timedelta(milliseconds=payload["ttl_ms"])
|
||||
if subscription.expires_at:
|
||||
expiry = min(expiry, subscription.expires_at)
|
||||
response = {"contract": CONTRACT, "policy_version": POLICY_VERSION, "request_id": payload["request_id"],
|
||||
"node_slug": current.slug, "boot_id": payload["boot_id"], "session_id": payload["session_id"],
|
||||
"account_id": user.pk, "subscription_id": subscription.pk, "credential_uuid": str(subscription.credential_uuid),
|
||||
"direction": payload["direction"], "requested_bytes": payload["requested_bytes"], "ttl_ms": payload["ttl_ms"],
|
||||
"issued_at": now.isoformat(), "expires_at": expiry.isoformat(), "executor_epoch": executor.epoch,
|
||||
"sequence": payload["sequence"], "enforced": False, "exempt": exempt,
|
||||
"kind": "bandwidth_exemption_lease" if exempt else "byte_credit"}
|
||||
if exempt:
|
||||
response["exemption_policy_key"] = ACCOUNT_BANDWIDTH_EXCEPTION_KEY
|
||||
else:
|
||||
response.update(granted_bytes=granted, rate_bytes_per_second=rate, burst_bytes=capacity // MICRO)
|
||||
encoded = json.dumps(response, sort_keys=True, separators=(",", ":"))
|
||||
if len(encoded.encode()) > MAX_RESPONSE_BYTES:
|
||||
raise BudgetRejected("budget_unavailable", 503)
|
||||
values = dict(user=user, executor_epoch=executor.epoch, credential_uuid=subscription.credential_uuid,
|
||||
session_id=payload["session_id"], sequence=payload["sequence"], fingerprint=fingerprint,
|
||||
response=encoded, issued_at=now)
|
||||
if lane is None:
|
||||
AccountBandwidthLane.objects.using(DB).create(node=current, subscription=subscription, direction=payload["direction"], **values)
|
||||
else:
|
||||
for key, value in values.items():
|
||||
setattr(lane, key, value)
|
||||
lane.save(using=DB)
|
||||
executor.clock_floor = now
|
||||
executor.save(using=DB, update_fields=["clock_floor"])
|
||||
return response
|
||||
|
||||
|
||||
def _http(request, action):
|
||||
if getattr(settings, "ACCOUNT_BANDWIDTH_BUDGET_V2_ENABLED", False) is not True:
|
||||
return _reply({"error_code": "budget_disabled"}, 503)
|
||||
from control.views import _authenticate_node
|
||||
try:
|
||||
_require_primary_backend()
|
||||
node = _authenticate_node(request)
|
||||
if not _node_allowed(node):
|
||||
raise BudgetRejected("node_not_authorized", 401)
|
||||
if action == "read":
|
||||
return _reply(read_executor(node))
|
||||
if len(request.body) > 4096:
|
||||
raise ValueError("budget payload too large")
|
||||
payload = json.loads(request.body, object_pairs_hook=_unique_json_pairs)
|
||||
return _reply(open_executor(node, payload) if action == "open" else issue_credit_v2(node, payload))
|
||||
except BudgetRejected as exc:
|
||||
return _reply({"error_code": exc.code}, exc.status)
|
||||
except (ValueError, TypeError, OverflowError):
|
||||
return _reply({"error_code": "invalid_budget_request"}, 400)
|
||||
except (DatabaseError, IntegrityError):
|
||||
return _reply({"error_code": "budget_unavailable"}, 503)
|
||||
|
||||
|
||||
@csrf_exempt
|
||||
@require_http_methods(["GET", "POST"])
|
||||
def node_budget_executor(request):
|
||||
return _http(request, "read" if request.method == "GET" else "open")
|
||||
|
||||
|
||||
@csrf_exempt
|
||||
@require_http_methods(["POST"])
|
||||
def node_bandwidth_budget_v2(request):
|
||||
return _http(request, "credit")
|
||||
|
||||
|
||||
+58
@@ -0,0 +1,58 @@
|
||||
"""Account configuration only; does not activate the disabled budget executor."""
|
||||
import django.core.validators
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
def lock_accounts_before_policy_ddl(apps, schema_editor):
|
||||
User = apps.get_model("accounts", "User")
|
||||
Policy = apps.get_model("shared_budget", "AccountBandwidthPolicy")
|
||||
if schema_editor.connection.vendor == "postgresql":
|
||||
# Serialize registration and policy edits for complete coverage. The
|
||||
# existing fixed-ID exemption and every owner policy byte stay intact.
|
||||
quote = schema_editor.connection.ops.quote_name
|
||||
with schema_editor.connection.cursor() as cursor:
|
||||
cursor.execute("LOCK TABLE " + quote(User._meta.db_table) + " IN SHARE MODE")
|
||||
cursor.execute("LOCK TABLE " + quote(Policy._meta.db_table) + " IN SHARE ROW EXCLUSIVE MODE")
|
||||
|
||||
|
||||
def set_ordinary_account_defaults(apps, schema_editor):
|
||||
User = apps.get_model("accounts", "User")
|
||||
Policy = apps.get_model("shared_budget", "AccountBandwidthPolicy")
|
||||
database = schema_editor.connection.alias
|
||||
ordinary = User.objects.using(database).exclude(pk=5)
|
||||
policies = Policy.objects.using(database)
|
||||
policies.exclude(user_id=5).update(upload_limit_kib_per_second=500, download_limit_kib_per_second=500)
|
||||
missing = ordinary.exclude(pk__in=policies.values("user_id")).values_list("pk", flat=True)
|
||||
policies.bulk_create([Policy(user_id=pk, upload_limit_kib_per_second=500, download_limit_kib_per_second=500)
|
||||
for pk in missing], batch_size=1000)
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
dependencies = [("shared_budget", "0001_initial")]
|
||||
operations = [
|
||||
# Must precede every DDL table lock: registration holds User first and
|
||||
# its post_save signal writes Policy. Acquiring Policy DDL first could
|
||||
# deadlock that transaction when we subsequently lock User.
|
||||
migrations.RunPython(lock_accounts_before_policy_ddl, migrations.RunPython.noop),
|
||||
migrations.RemoveConstraint(model_name="accountbandwidthpolicy", name="sb_policy_upload_bounded"),
|
||||
migrations.RemoveConstraint(model_name="accountbandwidthpolicy", name="sb_policy_download_bounded"),
|
||||
migrations.RemoveConstraint(model_name="accountbandwidthbucket", name="bandwidth_bucket_rate_bounded"),
|
||||
migrations.RemoveConstraint(model_name="accountbandwidthbucket", name="bandwidth_bucket_credit_bounded"),
|
||||
migrations.AlterField(model_name="accountbandwidthpolicy", name="upload_limit_kib_per_second",
|
||||
field=models.PositiveSmallIntegerField("账号上传上限(KiB/s)", default=500, db_default=500,
|
||||
validators=[django.core.validators.MinValueValidator(1), django.core.validators.MaxValueValidator(10240)])),
|
||||
migrations.AlterField(model_name="accountbandwidthpolicy", name="download_limit_kib_per_second",
|
||||
field=models.PositiveSmallIntegerField("账号下载上限(KiB/s)", default=500, db_default=500,
|
||||
validators=[django.core.validators.MinValueValidator(1), django.core.validators.MaxValueValidator(10240)])),
|
||||
migrations.AddConstraint(model_name="accountbandwidthpolicy", constraint=models.CheckConstraint(
|
||||
condition=models.Q(upload_limit_kib_per_second__gte=1, upload_limit_kib_per_second__lte=10240), name="sb_policy_upload_bounded")),
|
||||
migrations.AddConstraint(model_name="accountbandwidthpolicy", constraint=models.CheckConstraint(
|
||||
condition=models.Q(download_limit_kib_per_second__gte=1, download_limit_kib_per_second__lte=10240), name="sb_policy_download_bounded")),
|
||||
migrations.AddConstraint(model_name="accountbandwidthbucket", constraint=models.CheckConstraint(
|
||||
condition=models.Q(rate_bytes_per_second__gte=1, rate_bytes_per_second__lte=10485760), name="bandwidth_bucket_rate_bounded")),
|
||||
migrations.AddConstraint(model_name="accountbandwidthbucket", constraint=models.CheckConstraint(
|
||||
condition=models.Q(available_microbytes__lte=2097152000000), name="bandwidth_bucket_credit_bounded")),
|
||||
# Irreversible data policy: an automatic downgrade must not overwrite
|
||||
# later administrator choices or silently recreate 200 KiB/s limits.
|
||||
migrations.RunPython(set_ordinary_account_defaults),
|
||||
]
|
||||
@@ -0,0 +1,149 @@
|
||||
from django.conf import settings
|
||||
from django.core.exceptions import ValidationError
|
||||
from django.core.validators import MaxValueValidator, MinValueValidator
|
||||
from django.db import models
|
||||
from control.models import Node, Subscription
|
||||
|
||||
from .policy import DEFAULT_KIB_PER_SECOND, MAX_KIB_PER_SECOND, MAX_BYTES_PER_SECOND, MAX_BUCKET_MICROBYTES
|
||||
|
||||
ACCOUNT_BANDWIDTH_EXCEPTION_KEY = "owner-approved-20261022"
|
||||
APPROVED_EXEMPT_USER_ID = 5
|
||||
|
||||
|
||||
class AccountBandwidthPolicy(models.Model):
|
||||
user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE,
|
||||
primary_key=True, related_name="shared_bandwidth_policy")
|
||||
upload_limit_kib_per_second = models.PositiveSmallIntegerField(
|
||||
"账号上传上限(KiB/s)", default=DEFAULT_KIB_PER_SECOND, db_default=DEFAULT_KIB_PER_SECOND,
|
||||
validators=[MinValueValidator(1), MaxValueValidator(MAX_KIB_PER_SECOND)])
|
||||
download_limit_kib_per_second = models.PositiveSmallIntegerField(
|
||||
"账号下载上限(KiB/s)", default=DEFAULT_KIB_PER_SECOND, db_default=DEFAULT_KIB_PER_SECOND,
|
||||
validators=[MinValueValidator(1), MaxValueValidator(MAX_KIB_PER_SECOND)])
|
||||
|
||||
class Meta:
|
||||
verbose_name = "账户带宽策略"
|
||||
verbose_name_plural = "账户带宽策略"
|
||||
constraints = [
|
||||
models.CheckConstraint(condition=models.Q(upload_limit_kib_per_second__gte=1,
|
||||
upload_limit_kib_per_second__lte=MAX_KIB_PER_SECOND), name="sb_policy_upload_bounded"),
|
||||
models.CheckConstraint(condition=models.Q(download_limit_kib_per_second__gte=1,
|
||||
download_limit_kib_per_second__lte=MAX_KIB_PER_SECOND), name="sb_policy_download_bounded"),
|
||||
]
|
||||
|
||||
def __str__(self):
|
||||
return str(self.user)
|
||||
|
||||
|
||||
class ProtectedExemptionQuerySet(models.QuerySet):
|
||||
def update(self, **kwargs):
|
||||
raise ValidationError("受控豁免不能通过普通查询修改。")
|
||||
|
||||
def delete(self):
|
||||
raise ValidationError("受控豁免不能通过普通查询删除。")
|
||||
|
||||
def bulk_create(self, *args, **kwargs):
|
||||
raise ValidationError("受控豁免仅可通过审核后的数据迁移建立。")
|
||||
|
||||
def bulk_update(self, *args, **kwargs):
|
||||
raise ValidationError("受控豁免不能通过普通查询修改。")
|
||||
|
||||
|
||||
class AccountBandwidthExemption(models.Model):
|
||||
policy_key = models.CharField(primary_key=True, max_length=64,
|
||||
default=ACCOUNT_BANDWIDTH_EXCEPTION_KEY, editable=False)
|
||||
user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.PROTECT,
|
||||
related_name="shared_bandwidth_exemption", editable=False)
|
||||
created_at = models.DateTimeField(auto_now_add=True)
|
||||
objects = ProtectedExemptionQuerySet.as_manager()
|
||||
|
||||
class Meta:
|
||||
verbose_name = "受控账号免限速绑定"
|
||||
verbose_name_plural = "受控账号免限速绑定"
|
||||
default_permissions = ("view",)
|
||||
constraints = [models.CheckConstraint(
|
||||
condition=models.Q(policy_key=ACCOUNT_BANDWIDTH_EXCEPTION_KEY, user_id=APPROVED_EXEMPT_USER_ID),
|
||||
name="sb_single_approved_exemption")]
|
||||
|
||||
def save(self, *args, **kwargs):
|
||||
raise ValidationError("受控豁免仅可通过审核后的数据迁移建立。")
|
||||
|
||||
def delete(self, *args, **kwargs):
|
||||
raise ValidationError("受控豁免不能由普通后台操作删除。")
|
||||
|
||||
|
||||
class AccountBandwidthBucket(models.Model):
|
||||
"""Primary-DB account/direction credit, shared by every subscription/node.
|
||||
|
||||
Microbytes preserve sub-byte refill fractions without floating point. These
|
||||
rows and the grant ledger are authorizations, not traffic measurements.
|
||||
"""
|
||||
|
||||
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT,
|
||||
related_name="bandwidth_budget_buckets")
|
||||
direction = models.CharField(max_length=8, choices=[("upload", "upload"), ("download", "download")])
|
||||
available_microbytes = models.PositiveBigIntegerField(default=0)
|
||||
rate_bytes_per_second = models.PositiveIntegerField()
|
||||
exempt = models.BooleanField(default=False)
|
||||
refilled_at = models.DateTimeField()
|
||||
|
||||
class Meta:
|
||||
default_permissions = ()
|
||||
constraints = [
|
||||
models.UniqueConstraint(fields=["user", "direction"], name="unique_account_bandwidth_bucket"),
|
||||
models.CheckConstraint(condition=models.Q(direction__in=["upload", "download"]),
|
||||
name="bandwidth_bucket_direction"),
|
||||
models.CheckConstraint(condition=models.Q(rate_bytes_per_second__gte=1,
|
||||
rate_bytes_per_second__lte=MAX_BYTES_PER_SECOND),
|
||||
name="bandwidth_bucket_rate_bounded"),
|
||||
models.CheckConstraint(condition=models.Q(available_microbytes__lte=MAX_BUCKET_MICROBYTES),
|
||||
name="bandwidth_bucket_credit_bounded"),
|
||||
]
|
||||
|
||||
|
||||
class AccountBandwidthExecutor(models.Model):
|
||||
"""One durable fencing generation per node; never reset/delete on restart."""
|
||||
|
||||
node = models.OneToOneField(Node, on_delete=models.PROTECT, primary_key=True,
|
||||
related_name="bandwidth_budget_executor")
|
||||
epoch = models.PositiveBigIntegerField()
|
||||
boot_id = models.UUIDField()
|
||||
registration_id = models.UUIDField()
|
||||
opened_at = models.DateTimeField()
|
||||
clock_floor = models.DateTimeField()
|
||||
|
||||
class Meta:
|
||||
default_permissions = ()
|
||||
constraints = [models.CheckConstraint(condition=models.Q(epoch__gte=1, epoch__lte=9223372036854775807),
|
||||
name="bandwidth_executor_epoch_bounded")]
|
||||
|
||||
|
||||
class AccountBandwidthLane(models.Model):
|
||||
"""Fixed one-response replay slot, not a per-RPC ledger.
|
||||
|
||||
Same-epoch sequence/session state must never be reset. Older-epoch rows may
|
||||
be reused only while holding the durable node executor fence.
|
||||
"""
|
||||
|
||||
node = models.ForeignKey(Node, on_delete=models.PROTECT, related_name="bandwidth_budget_lanes")
|
||||
subscription = models.ForeignKey(Subscription, on_delete=models.PROTECT, related_name="bandwidth_budget_lanes")
|
||||
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT, related_name="bandwidth_budget_lanes")
|
||||
direction = models.CharField(max_length=8, choices=[("upload", "upload"), ("download", "download")])
|
||||
executor_epoch = models.PositiveBigIntegerField()
|
||||
credential_uuid = models.UUIDField()
|
||||
session_id = models.UUIDField()
|
||||
sequence = models.PositiveBigIntegerField()
|
||||
fingerprint = models.CharField(max_length=64)
|
||||
response = models.CharField(max_length=2048)
|
||||
issued_at = models.DateTimeField()
|
||||
|
||||
class Meta:
|
||||
default_permissions = ()
|
||||
constraints = [
|
||||
models.UniqueConstraint(fields=["node", "subscription", "direction"], name="unique_account_bandwidth_lane"),
|
||||
models.CheckConstraint(condition=models.Q(direction__in=["upload", "download"]), name="bandwidth_lane_direction"),
|
||||
models.CheckConstraint(condition=models.Q(executor_epoch__gte=1, executor_epoch__lte=9223372036854775807,
|
||||
sequence__gte=1, sequence__lte=9223372036854775807),
|
||||
name="bandwidth_lane_identity_bounded"),
|
||||
]
|
||||
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
DEFAULT_KIB_PER_SECOND = 500
|
||||
MAX_KIB_PER_SECOND = 10240
|
||||
MAX_BYTES_PER_SECOND = MAX_KIB_PER_SECOND * 1024
|
||||
# Keep the DB credit bound aligned with the allocator's existing 200 ms burst.
|
||||
MAX_BUCKET_MICROBYTES = MAX_BYTES_PER_SECOND * 200 * 1000
|
||||
|
||||
|
||||
def _limit_in_bytes(value):
|
||||
if type(value) is not int or not 1 <= value <= MAX_KIB_PER_SECOND:
|
||||
raise ValueError(f"Account proxy speed request must be an integer in 1–{MAX_KIB_PER_SECOND} KiB/s.")
|
||||
return value * 1024
|
||||
@@ -0,0 +1,72 @@
|
||||
"""Read-only, request-scoped portal guidance; never infers a live VPN connection."""
|
||||
from django.conf import settings
|
||||
from django.urls import reverse
|
||||
|
||||
from control.models import PlanApplication, Subscription
|
||||
from .models import AccountBandwidthExemption, AccountBandwidthExecutor
|
||||
from .policy import DEFAULT_KIB_PER_SECOND, MAX_KIB_PER_SECOND
|
||||
|
||||
|
||||
def portal_context(request):
|
||||
context = {"PLATFORM_NAME": "纵横家"}
|
||||
user = getattr(request, "user", None)
|
||||
if not user or not user.is_authenticated:
|
||||
return context
|
||||
|
||||
can_manage = bool(user.is_active and user.is_staff and (
|
||||
user.has_perm("shared_budget.view_accountbandwidthpolicy")
|
||||
or user.has_perm("shared_budget.change_accountbandwidthpolicy")))
|
||||
if can_manage:
|
||||
admin_budget = {
|
||||
"default_upload": DEFAULT_KIB_PER_SECOND, "default_download": DEFAULT_KIB_PER_SECOND,
|
||||
"maximum_limit": MAX_KIB_PER_SECOND,
|
||||
"allocator_enabled": getattr(settings, "ACCOUNT_BANDWIDTH_BUDGET_V2_ENABLED", False) is True,
|
||||
"policy_url": reverse("admin:shared_budget_accountbandwidthpolicy_changelist"),
|
||||
"execution_label": "待现场验收",
|
||||
}
|
||||
if user.has_perm("shared_budget.view_accountbandwidthexemption"):
|
||||
admin_budget["exemption_count"] = AccountBandwidthExemption.objects.count()
|
||||
admin_budget["exemption_url"] = reverse("admin:shared_budget_accountbandwidthexemption_changelist")
|
||||
admin_budget["registered_executors"] = AccountBandwidthExecutor.objects.count()
|
||||
context["admin_budget"] = admin_budget
|
||||
|
||||
match = getattr(request, "resolver_match", None)
|
||||
if not match or match.url_name != "portal-dashboard":
|
||||
return context
|
||||
# Every query is scoped to the signed-in user; no account ID is accepted
|
||||
# from query strings, form fields, or a selected client node.
|
||||
subscriptions = user.subscriptions.select_related("plan", "routing_policy").all()
|
||||
subscription = subscriptions.exclude(status__in=["cancelled", "expired"]).first() or subscriptions.first()
|
||||
pending = user.plan_applications.filter(status=PlanApplication.Status.PENDING).exists()
|
||||
journey = {"pending": pending, "ready": False, "step": 1,
|
||||
"primary_url": reverse("apply-plan"), "primary_label": "选择套餐并申请"}
|
||||
if not user.is_active or user.account_status in ("suspended", "departed"):
|
||||
journey.update(state="restricted", step=2, title="服务暂不可用",
|
||||
body="账号已暂停或停止服务,请联系管理员核实。当前页面不会提供订阅凭据。",
|
||||
primary_url=reverse("portal-dashboard") + "#application-history", primary_label="查看申请记录")
|
||||
elif subscription and subscription.is_usable:
|
||||
journey.update(state="ready", ready=True, step=3, title="订阅已准备好",
|
||||
body="下载 Windows 客户端后,用同一账号登录;也可展开个人订阅地址供兼容客户端使用。",
|
||||
primary_url=reverse("client-download-latest"), primary_label="下载 Windows 客户端")
|
||||
elif pending:
|
||||
journey.update(state="review", step=2, title="申请已提交,等待审核",
|
||||
body="不用重复提交。管理员核实身份并审核后,开通进度与订阅会显示在这里;暂未开放付款的套餐不会扣款。",
|
||||
primary_url=reverse("portal-dashboard") + "#application-history", primary_label="查看审核进度")
|
||||
elif subscription and subscription.online_payment_pending:
|
||||
journey.update(state="payment_pending", step=2, title="套餐暂未开放付款",
|
||||
body="申请只作登记,尚未扣款或开通付费服务。请等待管理员通知,不要向个人账号转账。",
|
||||
primary_url=reverse("portal-dashboard") + "#application-history", primary_label="查看申请记录")
|
||||
elif subscription and subscription.status == "active" and user.service_enabled:
|
||||
journey.update(state="provisioning", step=2, title="审核已通过,等待订阅就绪",
|
||||
body="节点配置仍在处理。请稍后刷新本页;实际连接状态只在客户端查看。",
|
||||
primary_url=reverse("portal-dashboard"), primary_label="刷新开通进度")
|
||||
elif subscription:
|
||||
journey.update(state="renew", step=2, title="订阅当前不可用",
|
||||
body="请核对下方有效期、流量和处理状态。需要续期或更换套餐时再提交申请。",
|
||||
primary_url=reverse("apply-plan"), primary_label="查看可申请套餐")
|
||||
else:
|
||||
journey.update(state="apply", title="先选择套餐,提交开通申请",
|
||||
body="注册只需一次。提交套餐申请后由管理员审核,通过后在这里获取订阅与客户端下载入口。")
|
||||
context["portal_journey"] = journey
|
||||
return context
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
{% if admin_budget %}
|
||||
<section class="admin-budget-panel" aria-labelledby="budget-heading">
|
||||
<div><span class="budget-eyebrow">账户共享带宽</span><h2 id="budget-heading">默认每方向 {{ admin_budget.default_upload }} KiB/s</h2>
|
||||
<p>同一账户的设备与节点共用上传、下载预算;单账户每方向可设 1–{{ admin_budget.maximum_limit|stringformat:"d" }} KiB/s。</p>
|
||||
<p>中央预算 API:{% if admin_budget.allocator_enabled %}<strong>已开启</strong>{% else %}<strong>未开启</strong>{% endif %} · 执行状态:<strong>{{ admin_budget.execution_label }}</strong></p>
|
||||
<p class="budget-detail">已注册执行器 {{ admin_budget.registered_executors }} 个。注册或开启 API 不代表真实限速已验收。{% if admin_budget.exemption_count != None %}受控豁免 {{ admin_budget.exemption_count }} 个,绑定固定账号 ID,不随邮箱转移。{% endif %}</p>
|
||||
</div>
|
||||
<div class="budget-links"><a class="budget-primary" href="{{ admin_budget.policy_url }}">管理账户限速</a>{% if admin_budget.exemption_url %}<a href="{{ admin_budget.exemption_url }}">查看只读豁免</a>{% endif %}</div>
|
||||
</section>
|
||||
{% endif %}
|
||||
Reference in New Issue
Block a user