Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions .github/workflows/main.yml
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,9 @@ name: CI/CD Pipeline

on:
push:
branches: [ main, master ]
branches: [ main, master, sg-4.x, sg-3.x-rest ]
pull_request:
branches: [ main, master ]
branches: [ main, master, sg-4.x, sg-3.x-rest ]

jobs:
super-linter:
Expand Down
93 changes: 86 additions & 7 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
# Sync Gateway Sync Function Tester

> **This branch (`sg-4.x`) targets Sync Gateway 4.x and its version vectors.**
> For Sync Gateway 3.x (revision tree `_rev` IDs) use the
> [`sg-3.x-rest`](../../tree/sg-3.x-rest) branch.

## PROBLEM

Don't want to touch the Sync Gateway Sync Function with a 10-foot pole because who knows what's going to happen to your writes and channel process when you change it?
Expand Down Expand Up @@ -27,7 +31,7 @@ This script will:
The script will do all the above as different user(s) from the `config.json` file.

## REQUIREMENTS
- A Running Sync Gateway w/ one or more known Sync Gateway USERS (cbl user)
- A running **Sync Gateway 4.x** with one or more known Sync Gateway USERS (cbl user). Don't have one? See [Local SG 4.x test stack](#local-sg-4x-test-stack-docker).
- Python 3
- Python Requests Library: https://docs.python-requests.org/en/latest/index.html

Expand All @@ -36,6 +40,46 @@ To install the required library:
pip install requests
```

## SYNC GATEWAY 4.x: VERSION VECTORS

Sync Gateway 4.0+ tracks document versions with a **version vector**
(Hybrid Logical Vector, HLV) instead of the CouchDB-style revision tree.
Every document now has a **Current Version (CV)**, returned as `cv` on writes
and `_cv` on reads:

```json
{"_id": "foo", "_rev": "1-092afbe9a5776a13d72efe4dd780051b",
"_cv": "18e8e11501350000@+RTUz3ZWvU8ktL6AuG0csA", "channels": ["bob"]}
```

A CV is `<version>@<source ID>`. Treat it as an opaque string. `_rev` is still
returned so Couchbase Lite clients older than 4.0 keep working, but
conflicts are now settled by the version vector (last write wins).

What the tester does differently on 4.x:

| | SG 3.x branch | SG 4.x branch (this one) |
|---|---|---|
| Version sent on `PUT` | body `_rev` | body `_cv` (current CV, read first) |
| Version sent on `DELETE` | `?rev=<rev>` | `?rev=<URL-encoded CV>`. CVs contain `@` and `+`, and an unencoded `+` gets a `400` |
| `_rev` / `_cv` in your JSON files | sent as-is | stripped; the tester always sends the live CV |
| `CHANGES` | `changes: [{"rev": ...}]` | adds `version_type=cv`, so `changes: [{"cv": ...}]` |
| `GET_RAW` | `_sync` | also logs the `_vv` xattr (the version vector: `src`, `ver`, ...) |
| New `CONFLICT` op | – | writes with a stale CV and expects `409` |
| Failed request | logged as `null` | logged with status + SG reason, e.g. `{"status": 403, "error": "Forbidden", "reason": "sg missing role"}` |

The `reason` on a 403 is the message from your Sync Function
(`throw({forbidden: "..."})`, `requireRole`, `requireAdmin`, ...), so you can
see *why* a write was denied.

If a user is allowed to write a document but not read it, the tester reads the
current CV through the admin port (when admin credentials are configured) so
the Sync Function's decision on the write is still tested. The log shows an
`[info]` line when this happens.

Docs: [Sync Gateway: Version Vectors (4.0+)](https://docs.couchbase.com/sync-gateway/current/manage/revisions.html#version-vectors-4-0) ·
[HLV data in xattrs](https://docs.couchbase.com/server/current/learn/clusters-and-availability/xdcr-enable-crossclusterversioning.html#hlv-data-maintained-in-xattr)

## HOW TO USE

**Step 1.** Update the `config.json` with your Sync Gateway hostname, one or more CBL test users, and other settings you want.
Expand All @@ -52,9 +96,12 @@ python3 sg_sync_function_tester.py config.json

Example output:
```
2024-07-22T17:06:30.000 - INFO - [success] - [GET] - [bob] - GET result for [foo] - {"_id": "foo", "_rev": "4-42bc40048cf41b74565750f2d2c55b28", "channels": ["bob"], "dateTimeStamp": "2024-07-22T17:03:56.604936"}
2024-07-22T17:06:30.000 - INFO - [success] - [PUT] - [bob] - PUT result for [foo] - {"id": "foo", "ok": true, "rev": "5-b9b6eb547de2d751b83457c29610994c"}
2024-07-22T17:06:30.000 - INFO - [success] - [CHANGES] - [bob] - Changes feed result for [foo], rows: 2 - {"results": [{"seq": 1, "id": "_user/bob", "changes": []}, {"seq": 163, "id": "foo", "changes": [{"rev": "5-b9b6eb547de2d751b83457c29610994c"}]}], "last_seq": "163"}
2026-11-17T10:14:15.509 - INFO - [info] - Sync Gateway version 4.1
2026-11-17T10:14:15.524 - INFO - [success] - [GET] - [bob] - GET result for [foo] - {"_cv": "18e8e131cd0c0000@+RTUz3ZWvU8ktL6AuG0csA", "_id": "foo", "_rev": "1-7386c0f700b338102e90403bca08d2cf", "channels": ["bob"], "dateTimeStamp": "2026-11-17T10:14:15.517366"}
2026-11-17T10:14:15.530 - INFO - [success] - [PUT] - [bob] - PUT result for [foo] - {"id": "foo", "ok": true, "rev": "2-5c9c41a168d0848aabdb2ef44427688d", "cv": "18e8e131cd8a0000@+RTUz3ZWvU8ktL6AuG0csA"}
2026-11-17T10:14:15.534 - INFO - [success] - [CONFLICT] - [bob] - CONFLICT result for [foo] (expect 409) - {"status": 409, "error": "conflict", "reason": "Document revision conflict"}
2026-11-17T10:14:15.549 - INFO - [failed] - [DELETE] - [bob] - DELETE result for [foo] - {"status": 403, "error": "Forbidden", "reason": "sg missing role"}
2026-11-17T10:14:15.631 - INFO - [failed] - [PUT] - [bob] - PUT result for [lk] - {"status": 403, "error": "Forbidden", "reason": "sg admin required"}

```

Expand All @@ -63,14 +110,15 @@ Example output:
The script supports the following operations:

- `GET`: Retrieve a document
- `GET_RAW`: Retrieve a document with full meta data `_sync` (admin only)
- `GET_RAW`: Retrieve a document with full meta data `_sync` and the `_vv` version vector (admin only)
- `PUT`: Create or update a document
- `DELETE`: Delete a document
- `CHANGES`: Get the changes feed. To filter channel(s) on the change just add your channel(s) names: `CHANGES:bob` or `CHANGES:bob,water`
- `CONFLICT`: `PUT` with a stale CV. Logged `[success]` when Sync Gateway correctly rejects it with `409`
- `PURGE`: Purge a document (admin only)
- `SLEEP`: Pause execution for a specified number of seconds

Admin versions of operations are available by appending `_ADMIN` to the operation name (e.g., `GET_ADMIN`, `PUT_ADMIN`).
Admin versions of operations are available by appending `_ADMIN` to the operation name (e.g., `GET_ADMIN`, `PUT_ADMIN`, `CONFLICT_ADMIN`). `PURGE` and `GET_RAW` always run as admin, once per document.

<mark style="background-color: yellow;">**Warning**</mark>: If you do `CHANGES_ADMIN` without a channel filter like `CHANGES_ADMIN:bob` Sync Gateway will process your whole database `_changes` feed in the output.

Expand Down Expand Up @@ -102,6 +150,7 @@ You can copy and paste the `config.json` file and rename them to run tests. `exa
python3 sg_sync_function_tester.py 1.user_put-user_get.json
python3 sg_sync_function_tester.py 2.user_put-user_changes.json
python3 sg_sync_function_tester.py 3.admin_put-user_delete.json
python3 sg_sync_function_tester.py 4.sg4_cv_conflict.json
```
**PRO TIP** The config `3.admin_put-user_delete.json` is a great way to see if the user can delete "READ-ONLY" documents.

Expand All @@ -123,7 +172,7 @@ python3 sg_sync_function_tester.py 3.admin_put-user_delete.json
"jsonFolder": "jsons", // Folder containing all your individual json files
"logPathToWriteTo": "sync_gateway_log",
"debug": false,
"operations": ["GET", "PUT", "DELETE", "CHANGES", "GET_ADMIN", "PUT_ADMIN", "DELETE_ADMIN", "CHANGES_ADMIN","SLEEP:3","GET_RAW","PURGE"] // Specify the order of operations and/or indivdual operations
"operations": ["GET", "PUT", "CONFLICT", "DELETE", "CHANGES", "GET_ADMIN", "PUT_ADMIN", "DELETE_ADMIN", "CHANGES_ADMIN","SLEEP:3","GET_RAW","PURGE"] // Specify the order of operations and/or indivdual operations
}
```

Expand All @@ -134,6 +183,31 @@ If your not using scopes and collections for mobile yet just leave the default v
"PURGE" is a great way to clean up data between tests. It literally 100% removes the document from Sync Gateway and the Couchbase Bucket. NOTE: PURGE is a Sync Gateway Admin function. In the config.json, you'll need to add Sync Admin (Couchbase Server RBAC [`Sync Gateway Architect`](https://docs.couchbase.com/server/current/learn/security/roles.html#sync-gateway-configurator) ) credentials for `sgAdminUser` and `sgAdminPassword`. Link here for [Offical Docs for: POST {db}/_purge](https://docs.couchbase.com/sync-gateway/current/rest-api-admin.html#/Document/post_keyspace__purge)


## LOCAL SG 4.x TEST STACK (Docker)

`docker/` brings up Couchbase Server 8.0.3 + Sync Gateway 4.1.2 with a
sample Sync Function ([docker/sync-function.js](docker/sync-function.js)) and
user `bob` / `12345`, matching the default `config.json`:

```sh
docker compose -f docker/docker-compose.yml up -d
./docker/setup.sh
python3 sg_sync_function_tester.py config.json
```

- Sync Gateway: public `http://localhost:4984`, admin `http://localhost:4985` (`Administrator` / `password`)
- Couchbase Server UI: `http://localhost:28091` (not published on 8091, so it won't clash with a local Couchbase install)
- Tear down: `docker compose -f docker/docker-compose.yml down -v`

The sample Sync Function denies `DELETE` without the `editor` role, denies
updates to `"locked": true` docs unless admin, and requires a `channels` field.
So `bob` gets useful `403`s to look at.

**Note:** XDCR between buckets in a Sync Gateway 4.x deployment requires
Couchbase Server 7.6.6+ and the bucket property `enableCrossClusterVersioning`.
It cannot be set when the bucket is created and cannot be turned off once
enabled. A single-cluster test setup like this one doesn't need it.

## UNDERSTANDING THE SYNC FUNCTION
Here is a link to understand what the Sync Function can and can not do.
- [Offical Docs for Sync Gateway's Sync Function](https://docs.couchbase.com/sync-gateway/current/sync-function.html#ex-sync-function)
Expand All @@ -155,6 +229,11 @@ Here is a link to understand what the Sync Function can and can not do.
6. **HTTP GET /_raw/{docId}**: Added a new `GET_RAW` operation that allows you to get the document from Sync Gateway exactly how it is stored in Couchbase Server includes all the meta / bookkeeping data from `_sync`.
7. **Scopes and Collection**: In the `config.json` just pass in non-default(`_default`) value for `sgDbScope` and `sgDbCollection` to test scopes and collection Sync Functions.
8. **Changes Channel(s) Filter**: Add the channel(s) you want to filter by in the changes operation like this:`CHANGES:bob` .
9. **Sync Gateway 4.x / Version Vectors**: Writes and deletes use the document's Current Version (`_cv`) instead of `_rev`; CVs are URL-encoded; `CHANGES` uses `version_type=cv`; `GET_RAW` logs the `_vv` xattr.
10. **CONFLICT Operation**: Verifies that a write with a stale CV is rejected with `409`.
11. **Failure Reasons in Logs**: Failed requests log the HTTP status and Sync Gateway's reason (e.g. the Sync Function's `forbidden` message) instead of `null`.
12. **Scopes & Collections fixes**: `CHANGES` and `PURGE` now use the configured scope/collection keyspace.
13. **Docker test stack**: `docker/` spins up Couchbase Server + Sync Gateway 4.x locally.


Works on My Computer - Tested & Certified ;-)
1 change: 1 addition & 0 deletions config.json
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
"operations":[
"PUT",
"GET",
"CONFLICT",
"DELETE",
"CHANGES",
"PUT_ADMIN",
Expand Down
30 changes: 30 additions & 0 deletions docker/docker-compose.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
# Local SG 4.x + Couchbase Server stack for testing the tester.
# docker compose -f docker/docker-compose.yml up -d
# ./docker/setup.sh
# Server ports are NOT published on 8091/11210 (to avoid clashing with a local
# Couchbase install); the web UI is on http://localhost:28091.
name: sg4-tester

services:
cb-server:
image: couchbase/server:enterprise-8.0.3
ports:
- "28091:8091"
healthcheck:
test: ["CMD", "curl", "-sf", "http://localhost:8091/ui/index.html"]
interval: 5s
retries: 30

sync-gateway:
image: couchbase/sync-gateway:4.1.2-enterprise
depends_on:
cb-server:
condition: service_healthy
# SG exits if the bucket/user don't exist yet; keep retrying until setup.sh runs.
restart: on-failure
command: ["/etc/sync_gateway/sg-bootstrap.json"]
volumes:
- ./sg-bootstrap.json:/etc/sync_gateway/sg-bootstrap.json:ro
ports:
- "4984:4984"
- "4985:4985"
53 changes: 53 additions & 0 deletions docker/setup.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
#!/usr/bin/env bash
# One-time setup of the local SG 4.x test stack (idempotent-ish: re-running is safe).
set -euo pipefail
cd "$(dirname "$0")"

COMPOSE="docker compose -f docker-compose.yml"
CB_ADMIN=Administrator
CB_PASS=password
BUCKET=sync_gateway
SG_ADMIN="http://localhost:4985"

# wait_for <desc> <cmd...> : retry cmd every 2s, give up after 3 minutes
wait_for() { local d=$1; shift; for _ in $(seq 1 90); do "$@" >/dev/null 2>&1 && return 0; sleep 2; done; echo "Timed out waiting for $d" >&2; exit 1; }

echo "==> Waiting for Couchbase Server..."
wait_for "Couchbase Server" $COMPOSE exec -T cb-server curl -sf http://localhost:8091/ui/index.html

echo "==> Initialising cluster"
$COMPOSE exec -T cb-server couchbase-cli cluster-init -c localhost \
--cluster-username "$CB_ADMIN" --cluster-password "$CB_PASS" \
--services data,index,query --cluster-ramsize 1024 --cluster-index-ramsize 256 \
--index-storage-setting default || echo " (already initialised)"

echo "==> Creating bucket $BUCKET"
$COMPOSE exec -T cb-server couchbase-cli bucket-create -c localhost \
-u "$CB_ADMIN" -p "$CB_PASS" --bucket "$BUCKET" --bucket-type couchbase \
--bucket-ramsize 256 --wait || echo " (bucket exists)"

echo "==> Creating RBAC user sync_gateway"
$COMPOSE exec -T cb-server couchbase-cli user-manage -c localhost \
-u "$CB_ADMIN" -p "$CB_PASS" --set --rbac-username sync_gateway \
--rbac-password password --auth-domain local \
--roles "mobile_sync_gateway[*]"

echo "==> Waiting for Sync Gateway admin API..."
wait_for "Sync Gateway" curl -sf -u "$CB_ADMIN:$CB_PASS" "$SG_ADMIN/"
curl -s -u "$CB_ADMIN:$CB_PASS" "$SG_ADMIN/"; echo

echo "==> Creating SG database $BUCKET"
SYNC_FN=$(python3 -c 'import json,sys;print(json.dumps(open("sync-function.js").read()))')
curl -s -u "$CB_ADMIN:$CB_PASS" -X PUT "$SG_ADMIN/$BUCKET/" \
-H 'Content-Type: application/json' \
-d "{\"bucket\":\"$BUCKET\",\"num_index_replicas\":0,\"sync\":$SYNC_FN}"; echo

db_online() { curl -sf -u "$CB_ADMIN:$CB_PASS" "$SG_ADMIN/$BUCKET/" | grep -q '"state":"Online"'; }
wait_for "database online" db_online

echo "==> Creating SG user bob"
curl -s -u "$CB_ADMIN:$CB_PASS" -X PUT "$SG_ADMIN/$BUCKET/_user/bob" \
-H 'Content-Type: application/json' \
-d '{"name":"bob","password":"12345","admin_channels":["bob"]}'; echo

echo "==> Done. Public: http://localhost:4984/$BUCKET Admin: $SG_ADMIN/$BUCKET CB UI: http://localhost:28091"
19 changes: 19 additions & 0 deletions docker/sg-bootstrap.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
{
"bootstrap": {
"server": "couchbase://cb-server",
"username": "sync_gateway",
"password": "password",
"use_tls_server": false
},
"api": {
"public_interface": ":4984",
"admin_interface": ":4985",
"metrics_interface": ":4986"
},
"logging": {
"console": {
"log_level": "info",
"log_keys": ["HTTP", "CRUD", "Sync", "Javascript"]
}
}
}
15 changes: 15 additions & 0 deletions docker/sync-function.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
function (doc, oldDoc, meta) {
// Deletes need the "editor" role -> bob (no roles) gets 403 on DELETE.
if (doc._deleted) {
requireRole("editor");
return;
}
// Docs flagged locked can only be written by an admin -> bob gets 403 on PUT.
if (doc.locked === true || (oldDoc && oldDoc.locked === true)) {
requireAdmin();
}
if (!doc.channels) {
throw({forbidden: "channels field is required"});
}
channel(doc.channels);
}
30 changes: 30 additions & 0 deletions example_configs/4.sg4_cv_conflict.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
{
"sgHost": "http://localhost",
"sgPort": "4984",
"sgAdminPort": "4985",
"sgDb": "sync_gateway",
"sgDbScope": "_default",
"sgDbCollection": "_default",
"sgTestUsers": [
{
"userName": "bob",
"password": "12345",
"sgSession": ""
}
],
"sgAdminUser": "Administrator",
"sgAdminPassword": "password",
"jsonFolder": "jsons",
"logPathToWriteTo": "sync_gateway_log",
"debug": false,
"operations": [
"PUT_ADMIN",
"GET",
"PUT",
"CONFLICT",
"DELETE",
"CHANGES:bob",
"GET_RAW",
"PURGE"
]
}
Loading
Loading