Files
floci/docs/services/redshift.md
T
Vũ Thế Huy 85180a4d88 feat(redshift): emulate Redshift COPY FROM s3 over Simple Query protocol (#3100)
* feat(redshift): parse COPY FROM s3 statements

* feat(redshift): simulate Redshift COPY FROM s3 via CopyIn

* feat(redshift): mediate the intercepting bridge pump with a backend lock

* feat(redshift): dispatch COPY FROM s3 via intercepting bridge

* test(redshift): cover COPY from S3 end to end

* docs(redshift): document COPY from S3 support

* fix(redshift): harden the S3 COPY simulator error and protocol handling

Address code review findings on the Part 4 COPY simulator:

- Guarantee exactly one client response on a mid-copy failure. The abort
  path sent CopyFail, relayed the backend's ErrorResponse/ReadyForQuery,
  then also synthesized its own, desynchronizing the client. It now emits
  one response: the backend's, or a synthesized one only when the backend
  is unreachable.
- Catch RuntimeException (AwsException) while streaming objects. A key that
  vanished between listing and reading previously propagated out of the
  bridge and closed the connection with the backend stuck in CopyIn.
- Reply to the client when the backend closes before CopyInResponse
  instead of returning silently and leaving the client blocked.
- Stop doubling backslashes when quoting DELIMITER / NULL values. Under
  standard_conforming_strings a backslash is literal, so NULL AS '\N' was
  reaching the backend as '\N' and nulls loaded as text.
- Reject COPY statements carrying an option the simulator cannot honour
  (PARQUET, JSON, MAXERROR, credentials, ...) or a trailing statement,
  so they fail open to PostgreSQL rather than loading with wrong framing.
- Scan option keywords with string literals blanked, so NULL AS 'csv' no
  longer flips the format and DELIMITER ';' no longer trips the trailing
  check.
- Report the failed-transaction status ('E') in a synthesized error when
  the client is in a transaction block; track it from the backend's
  ReadyForQuery in the bridge.
- Bound the backend read timeout during an owned exchange (60s) instead of
  blocking forever; back off between idle-wait retries.
- Relay asynchronous backend messages (NoticeResponse, ParameterStatus)
  to the client instead of dropping them; log every tolerated AwsException.
- Honour the BackendExchange return value so a future interceptor can
  decline before touching the backend.

Tests: cover the mid-copy abort (one E + one Z), backend EOF, literal
NULL AS '\N', the unsupported-clause and trailing-statement rejections,
failed-transaction status, plus a GZIP end-to-end case; the missing-object
integration test now seeds its own bucket.

* fix(redshift): address review feedback on COPY option parsing, prefix pagination, and tx state

* fix(redshift): handle backend tx abort sync failure and log socket close

* fix(redshift): verify backend transaction status 'E' after abort query
2026-09-05 23:46:49 -04:00

11 KiB

Redshift

Protocol: Query (XML) for the management API Management Endpoint: POST http://localhost:4566/ with Action= param Data Endpoint: Floci's auth proxy on the Endpoint and Port returned by DescribeClusters (PostgreSQL wire protocol)

Floci emulates Amazon Redshift by managing a real PostgreSQL Docker container per cluster behind a Redshift-shaped control plane. Each cluster sits behind a lightweight auth proxy on the Floci host, so the endpoint is reachable from outside Docker and the master password is validated at the proxy, a ModifyCluster password change takes effect for new connections immediately. Redshift speaks the PostgreSQL wire protocol, so the cluster endpoint returned by DescribeClusters works with any standard PostgreSQL driver (psql, JDBC, psycopg, …).

Always read the host and port from DescribeClusters rather than assuming a fixed port. PostgreSQL listens on 5432 inside the container; the port you connect to is dynamically assigned on the host and returned as Clusters[0].Endpoint.Port. Redshift's conventional port is 5439, but the emulator does not bind it: use whatever DescribeClusters reports.

The container has no persistent volume: if the physical container survives a Floci restart it is adopted and its data is kept, but if the container itself is gone (host reboot, docker rm, a pruned dev box) the cluster comes back empty. Use CreateClusterSnapshot / RestoreFromClusterSnapshot to preserve data explicitly.

Supported Actions

Action Description
CreateCluster Create a cluster and start a PostgreSQL container for it
DescribeClusters List clusters and their connection details
DeleteCluster Stop and remove a cluster and its container
CreateClusterSnapshot Back up a cluster to a SQL dump via pg_dump
DescribeClusterSnapshots List snapshots, optionally filtered by snapshot or cluster identifier
DeleteClusterSnapshot Remove a snapshot and its stored dump
RestoreFromClusterSnapshot Create a new cluster and load a snapshot's dump into it via psql
CreateClusterParameterGroup Register a parameter group (metadata only)
DescribeClusterParameterGroups List parameter groups, optionally filtered by name
DescribeClusterParameters Return the parameters of a group, with any values set by ModifyClusterParameterGroup
ModifyClusterParameterGroup Update parameter values on a group
DeleteClusterParameterGroup Remove a parameter group
CreateTags Add or overwrite tags on a cluster, snapshot, subnet group or parameter group
DeleteTags Remove tags by key from a resource
DescribeTags List tagged resources and their tags
CreateClusterSubnetGroup Register a cluster subnet group (metadata only)
DescribeClusterSubnetGroups List subnet groups, optionally filtered by name
ModifyClusterSubnetGroup Update a subnet group's description or subnet list
DeleteClusterSubnetGroup Remove a subnet group
ModifyCluster Update node type, parameter group, security groups, or the master password
RebootCluster Restart a cluster's container

Configuration

Variable Default Description
FLOCI_SERVICES_REDSHIFT_ENABLED true Enable or disable Redshift
FLOCI_SERVICES_REDSHIFT_IMAGE_VERSION postgres:15-alpine PostgreSQL Docker image backing each cluster
FLOCI_SERVICES_REDSHIFT_DEFAULT_PORT 5439 Reported Redshift port hint (the real host port is dynamic and comes from DescribeClusters)
FLOCI_SERVICES_REDSHIFT_PROXY_BASE_PORT 7100 Lowest host port the per-cluster auth proxies bind
FLOCI_SERVICES_REDSHIFT_PROXY_MAX_PORT 7199 Highest host port the per-cluster auth proxies bind
FLOCI_SERVICES_REDSHIFT_ENDPOINT_HOST (unset) Hostname advertised in DescribeClusters; unset resolves from the Docker host

Redshift needs the Docker socket so it can launch PostgreSQL containers. Each cluster's container is published on a dynamically assigned host port, returned by DescribeClusters.

Docker Compose

services:
  floci:
    image: floci/floci:latest
    ports:
      - "4566:4566"
    volumes:
      - /var/run/docker.sock:/var/run/docker.sock

For private registry authentication and other Docker settings see Docker Configuration.

Examples

Management API (AWS CLI)

export AWS_ENDPOINT_URL=http://localhost:4566
export AWS_DEFAULT_REGION=us-east-1
export AWS_ACCESS_KEY_ID=test
export AWS_SECRET_ACCESS_KEY=test

# Create a cluster (starts a PostgreSQL container)
aws redshift create-cluster \
  --cluster-identifier my-warehouse \
  --node-type dc2.large \
  --master-username admin \
  --master-user-password Secret123

# Read the cluster endpoint and port
aws redshift describe-clusters \
  --cluster-identifier my-warehouse \
  --query 'Clusters[0].Endpoint'

# Snapshot and restore
aws redshift create-cluster-snapshot \
  --snapshot-identifier snap-1 \
  --cluster-identifier my-warehouse
aws redshift restore-from-cluster-snapshot \
  --cluster-identifier my-warehouse-restored \
  --snapshot-identifier snap-1

# Delete
aws redshift delete-cluster \
  --cluster-identifier my-warehouse \
  --skip-final-cluster-snapshot

Data plane (Python + psycopg)

import psycopg

# Read host and port from DescribeClusters: the host port is dynamic.
host, port = "localhost", 32768  # e.g. Clusters[0].Endpoint.Address / .Port
with psycopg.connect(f"host={host} port={port} dbname=dev user=admin password=Secret123") as conn:
    conn.execute("CREATE TABLE people (name text)")
    conn.execute("INSERT INTO people VALUES ('Alice')")
    for row in conn.execute("SELECT * FROM people"):
        print(row)

Management API (Python / boto3)

import boto3

redshift = boto3.client(
    "redshift",
    endpoint_url="http://localhost:4566",
    region_name="us-east-1",
)

cluster = redshift.create_cluster(
    ClusterIdentifier="my-warehouse",
    NodeType="dc2.large",
    MasterUsername="admin",
    MasterUserPassword="Secret123",
)
print(cluster["Cluster"]["Endpoint"])

SQL Interceptor

Floci's Redshift auth proxy inspects frontend queries on the PostgreSQL wire protocol (Simple Query 'Q' protocol) and rewrites common Redshift-specific table DDL so it runs on the plain PostgreSQL backend.

DDL compatibility

  • Redshift-only table DDL keywords are stripped before the statement is forwarded: DISTSTYLE ALL|EVEN|KEY|AUTO, DISTKEY (<col>) and column-level DISTKEY, [COMPOUND|INTERLEAVED] SORTKEY (<cols>) and column-level SORTKEY, and ENCODE <codec> for the real Redshift column encodings (raw, az64, bytedict, delta, delta32k, lzo, mostly8, mostly16, mostly32, runlength, text255, text32k, zstd) or auto.
  • The rewrite only runs when the statement's first keyword is CREATE TABLE or ALTER TABLE. A SELECT, INSERT, function body, or string literal that merely contains one of these keywords is forwarded byte-for-byte. Single-quoted and dollar-quoted string literals are masked before the rewrite, so a keyword inside a quoted value (including in a later statement of a multi-statement query) is preserved.
  • Columns legitimately named distkey, sortkey, or encode survive.

COPY from S3

COPY <table> [(<columns>)] FROM 's3://<bucket>/<keyOrPrefix>' [options] sent over the Simple Query protocol is emulated: Floci reads the object (or every object under the prefix, in key order) through its own S3 service and streams the rows into the backing PostgreSQL container with COPY ... FROM STDIN.

  • Supported options: DELIMITER, FORMAT CSV (or a bare CSV), GZIP, IGNOREHEADER <n> and HEADER, NULL AS, and an explicit column list.
  • The default framing is pipe-delimited text, matching Redshift. FORMAT CSV switches to CSV with a comma default delimiter.
  • IGNOREHEADER and HEADER skip lines from the first resolved object only.
  • GZIP is the only input compression recognized; BZIP2, LZOP and ZSTD are not.
  • S3 access is authorized as an unsigned request: with FLOCI_SERVICES_S3_ENFORCE_AUTH off it is unrestricted; with it on, bucket policy and public access settings apply.
  • Any other clause (FIXEDWIDTH, JSON, PARQUET, AVRO, ORC, MANIFEST, MAXERROR, DATEFORMAT, TIMEFORMAT, REGION, ENCODING, ESCAPE, REMOVEQUOTES, BLANKSASNULL, EMPTYASNULL, TRUNCATECOLUMNS, ACCEPTINVCHARS, credentials clauses, and so on) is not recognized: the statement is forwarded unchanged and PostgreSQL returns its own error.
  • A multi-statement query whose COPY is followed by another statement is not intercepted; send the COPY on its own.
  • Extended Query protocol COPY (a JDBC PreparedStatement, or pgjdbc's default preferQueryMode=extended) is not intercepted. Use preferQueryMode=simple.

Limitations

  • Emulation runs on the Simple Query protocol ('Q') only. Extended Query protocol statements (Parse/Bind/Execute) pass through untouched, including anything a JDBC PreparedStatement sends, and, with the pgjdbc default preferQueryMode=extended, plain Statement calls too. Connect with preferQueryMode=simple to exercise the interceptor from JDBC.
  • The rewrite is textual (regex-based). It masks single-quoted string literals first, so DEFAULT / CHECK string values are safe, but it is not comment-aware and does not recognize escape strings (E'...'): an apostrophe inside a -- or /* */ comment can make the rewrite skip a Redshift clause. That fails safe: the statement then reaches PostgreSQL, which returns its own syntax error, but avoid apostrophes-in-comments in CREATE TABLE / ALTER TABLE.
  • A rewrite failure or any statement the interceptor does not recognize is forwarded unmodified (fail-open); PostgreSQL then rejects the Redshift-only syntax itself.
  • Simple Query ('Q') messages larger than 16 MiB bypass the interceptor and stream through verbatim without heap buffering; non-query traffic also streams through with no size limit.
  • UNLOAD (...) TO 's3://...' is not yet emulated (planned).

Out of Scope

  • Real Redshift SQL semantics: the data plane is stock PostgreSQL. Redshift-only table DDL keywords (DISTSTYLE / DISTKEY / SORTKEY / ENCODE) are stripped so CREATE TABLE / ALTER TABLE executes (see SQL Interceptor), but the distribution/sort behavior they request is not; UNLOAD to S3 and SUPER/SPECTRUM are not emulated.
  • Multi-node clusters: NodeType and NumberOfNodes are stored as metadata; every cluster is a single PostgreSQL container.
  • Parameter groups apply no real engine settings; values are stored and echoed back only.
  • Subnet groups, VPC routing, and security groups are metadata only.
  • Resize, pause/resume, IAM authentication, snapshot schedules, and cross-region snapshot copy.
  • The auth proxy validates only the master user's password. Non-master users pass straight through to PostgreSQL, which remains the authority for their credentials.
  • IAM database authentication (GetClusterCredentials), and sslmode=verify-full against the self-signed proxy certificate.