tencentdb_scf
tencentdb_scf is a dedicated TencentDB PostgreSQL extension that enables secure and controlled CloudBase cloud function invocations directly from SQL. It supports scenarios such as scheduled tasks, triggers, and business SQL-driven cloud function calls while avoiding SSRF, network pivot, and attack proxy risks associated with general-purpose HTTP extensions.
Installation
tencentdb_scf depends on the pgcrypto extension. Enable pgcrypto first:
CREATE EXTENSION IF NOT EXISTS pgcrypto;
CREATE EXTENSION IF NOT EXISTS tencentdb_scf;
The extension is always installed into the tencentdb_scf schema. If search_path is not configured, use the schema prefix when calling functions, e.g. tencentdb_scf.tencentdb_scf_post(...). You can also set the search path to simplify calls:
SET search_path = tencentdb_scf, public;
Core API
Configure CloudBase Environment
Configure the CloudBase environment ID and API Key before use:
SELECT tencentdb_scf.set_cloudbase_env_id('your-env-id');
SELECT tencentdb_scf.set_cloudbase_api_key('your-cloudbase-api-key');
set_cloudbase_env_id
Sets the CloudBase environment ID. The configuration is persisted to the tencentdb_scf.config table.
Syntax:
tencentdb_scf.set_cloudbase_env_id(env_id TEXT) RETURNS BOOLEAN
Constraints:
- Must not be empty
- Maximum length: 128
- Must not start with
- - Only lowercase letters, digits, and hyphens are allowed
set_cloudbase_api_key
Sets the CloudBase API Key. The value is encrypted using PGP symmetric encryption via pgcrypto and persisted.
Syntax:
tencentdb_scf.set_cloudbase_api_key(key TEXT) RETURNS BOOLEAN
Constraints:
- Must not be empty
- Maximum length: 4096
- Must not contain control characters
Invoke a Cloud Function
Sends a POST request to the CloudBase cloud function gateway.
Syntax:
tencentdb_scf.tencentdb_scf_post(
path TEXT,
headers JSONB DEFAULT '{}'::jsonb,
body TEXT DEFAULT '',
sync BOOLEAN DEFAULT true,
timeout_milliseconds INT DEFAULT 5000
) RETURNS BIGINT
Parameters:
| Parameter | Type | Default | Description |
|---|---|---|---|
path | TEXT | Required | CloudBase function path; must start with /v1/functions/ |
headers | JSONB | '{}' | Custom request headers (sensitive headers are automatically filtered) |
body | TEXT | '' | Request body content |
sync | BOOLEAN | true | true for synchronous, false for asynchronous |
timeout_milliseconds | INT | 5000 | Request timeout in milliseconds |
Returns: BIGINT request ID, which can be used to query the result.
Path constraints:
- Must not be empty
- Must start with
/v1/functions/ - Total length must not exceed 512
- Function name must not be empty and must start with a letter
- Function name may only contain letters, digits, hyphens, and underscores
- Function name must not end with a hyphen or underscore
Valid examples:
/v1/functions/myFunction
Invalid examples:
/functions/myFunction -- Missing /v1 prefix
https://xxx.api.tcloudbasegateway.com/... -- Full URL not accepted
/v1/functions/1bad -- Function name starts with a digit
/v1/functions/bad_ -- Function name ends with underscore
/v1/functions/bad.path -- Function name contains dot
Query Invocation Result
Queries the result of a specific request ID.
Syntax:
tencentdb_scf.tencentdb_scf_result(req_id BIGINT) RETURNS JSONB
Returns JSONB containing status code, content type, response headers, response body, timeout flag, error message, and creation time. Returns NULL if the request is not yet complete or the response has been cleaned up by TTL.
Usage Examples
Synchronous Invocation
Synchronous mode is the default. It is suitable for scenarios where you need immediate confirmation and the cloud function has a short execution time.
-- Initiate synchronous invocation and capture the returned request ID
SELECT tencentdb_scf.tencentdb_scf_post(
path := '/v1/functions/sendNotification',
headers := jsonb_build_object('X-Custom-Header', 'value'),
body := json_build_object('action', 'sendEmail', 'to', 'admin@example.com')::text,
sync := true,
timeout_milliseconds := 5000
) AS request_id;
-- Query the result using the request_id returned above
SELECT tencentdb_scf.tencentdb_scf_result(<request_id>);
Asynchronous Invocation
Asynchronous mode is suitable for triggers, batch jobs, and scheduled tasks where you do not want to block the main workflow. Asynchronous requests are written to tencentdb_scf.request_queue and consumed by the Background Worker after the transaction commits.
If the transaction rolls back, uncommitted requests will not be consumed by the worker.
-- Initiate asynchronous invocation and capture the returned request ID
SELECT tencentdb_scf.tencentdb_scf_post(
path := '/v1/functions/heavyTask',
headers := '{}'::jsonb,
body := json_build_object('dataset', 'large')::text,
sync := false,
timeout_milliseconds := 30000
) AS request_id;
-- Query the result using the request_id returned above
SELECT tencentdb_scf.tencentdb_scf_result(<request_id>);
Scheduled Invocation with pg_cron
CREATE OR REPLACE FUNCTION trigger_daily_cleanup()
RETURNS void AS $$
BEGIN
PERFORM tencentdb_scf.tencentdb_scf_post(
path := '/v1/functions/dailyCleanup',
headers := '{}'::jsonb,
body := json_build_object(
'action', 'cleanup',
'timestamp', now()::text
)::text,
sync := false,
timeout_milliseconds := 15000
);
END;
$$ LANGUAGE plpgsql;
SELECT cron.schedule(
'daily-cleanup',
'0 2 * * *',
'SELECT trigger_daily_cleanup()'
);
Security Design
URL Convergence
User SQL only receives a path. The full URL is constructed by the extension:
https://<env_id>.api.tcloudbasegateway.com<path>
Since env_id only allows lowercase letters, digits, and hyphens, users cannot inject protocol, port, path, user info, or other URL structural characters through env_id.
Request Validation
- Before execution, the checkurl SDK validates that only HTTPS and
api.tcloudbasegateway.com(and subdomains) are allowed - Both synchronous and asynchronous paths restrict the protocol to HTTPS and disable 30x auto-redirects
- The server-side always injects
Authorization: Bearer <api_key>andContent-Type: application/json
Header Protection
Users can pass custom headers via the headers JSONB parameter, but the following sensitive or protocol-semantic headers are filtered:
AuthorizationHostCookieX-Forwarded-ForX-Forwarded-HostX-Forwarded-ProtoContent-Type
Users should not include authentication info or Content-Type in headers. The current version always uses Content-Type: application/json. Users are not allowed to set, append, or override Content-Type to avoid duplicate headers causing inconsistent request body parsing at the gateway or cloud function layer.
Internal Objects
The extension creates the following internal tables under the tencentdb_scf schema:
| Table | Purpose |
|---|---|
config | Stores CloudBase environment ID and API Key (API Key encrypted via pgcrypto) |
request_queue | Asynchronous request queue populated by tencentdb_scf_post(..., sync := false) |
_http_response | Stores results of both synchronous and asynchronous invocations; queried by tencentdb_scf_result |
Notes
- Existing instances are not affected by default. You must explicitly install the extension and configure the CloudBase environment ID and API Key
- Only the POST method is currently supported. GET, PUT, DELETE, and other HTTP methods are not available
- Only the CloudBase gateway domain is allowed; arbitrary external domains are not supported
- Resource limiting GUCs such as concurrency, QPS, request body size, and response body size are not yet implemented in the current version
- Dedicated audit logging is not yet implemented in the current version