
swagger: "2.0"
info:
  title: Sync Gateway
  description: |+
    Documentation for the Sync Gateway Admin REST API.
  version: '3.0'
# the domain of the service
host: localhost:4985
# array of all schemes that your API supports
schemes:
- http
- https
# will be prefixed to all paths
consumes:
- application/json
# - application/javascript
produces:
- application/json
# - application/javascript
securityDefinitions:
  BasicAuth:
    type: basic

paths:
  /:
    get:
      tags:
      - Server
      operationId: get_server_metadata
      summary: Get Server Metadata
      description: |+
        Returns meta-information about the server.
      responses:
        200:
          description: Meta-information about the server.
          schema:
            $ref: '#/definitions/Server'
  /_config:
    get:
      operationId: 'get_server_configuration'
      tags:
      - Server
      - 'Bootstrap Configuration'
      summary: Get Server Configuration
      description: |+
        Returns the Sync Gateway configuration of the running instance.
        This is a good method to check if a particular key was set correctly on the config file.

        *Sync Gateway Roles Required (CBS 7.0.2 Developer Preview):*

        - Sync Gateway Dev Ops
      responses:
        200:
          $ref: '#/responses/200_startup_config'

    put:
      operationId: 'put_logging_options'
      tags:
      - Server
      - 'Bootstrap Configuration'
      - Logging
      summary: Update Logging Options
      description: |+
        Update bootstrap logging options without needing a restart

        *Sync Gateway Roles Required (CBS 7.0.2 Developer Preview):*

        - Sync Gateway Dev Ops
      parameters:
        - $ref: '#/parameters/bootstrap-logging'
      responses:
        200:
          description: Returned updated Bootstrap logging settings
          schema:
            $ref: '#/definitions/Logging_model'
  /_expvar:
    get:
      operationId: 'get_sync_gateway_statistics'
      tags:
      - Server
      summary: Get Sync Gateway Statistics
      description: |+
        The ```Expvar```method returns a number of runtime variables that you can view for debugging or performance monitoring purposes.

        This method can also be accessed using Sync Gateway's [Metrics REST API](rest-api-metrics.html)

        **See** : [Sync Gateway Statistics Schema](stats-monitoring.html) for more details on the metrics collected and reported by Sync Gateway.


        *Sync Gateway Roles Required (CBS 7.0.2 Developer Preview):*

        - Sync Gateway Dev Ops
        - External stats reader
      responses:
        200:
          description: OK - indicates success
          schema:
            $ref: '#/definitions/ExpVars'

  /_logging:
    get:
      operationId: 'get_logging_tags'
      tags:
      - Server
      summary: Get Logging Tags
      description: |+
        Get logging tags of running instance.

        *Sync Gateway Roles Required (CBS 7.0.2 Developer Preview):*

        - Sync Gateway Dev Ops
      responses:
        200:
          description: |+
            The response is a set of key-value pairs.
            The key is a log tag and the value is a boolean to indicate whether this tag is enabled.
          schema:
            $ref: '#/definitions/LogTags'
    put:
      operationId: 'logging_tags_put'
      tags:
      - Server
      summary: Set Logging Tags
      description: |+
        Enabling logging for a tag provides additional diagnostic information for that logging area.

        The PUT request replaces all existing logging tags with the ones specified in the request body.

        *Sync Gateway Roles Required (CBS 7.0.2 Developer Preview):*

        - Sync Gateway Dev Ops
      parameters:
      - $ref: '#/parameters/level'
      - $ref: '#/parameters/logLevel'
      - $ref: '#/parameters/logtags'
      responses:
        201:
          description: The operation was successful
    post:
      operationId: 'logging_tags_post'
      tags:
      - Server
      summary: Set Logging Tags
      description: |+
        Enabling logging for a tag provides additional diagnostic information for that logging area.

        The POST request only updates the tags specified in the request body.

        *Sync Gateway Roles Required (CBS 7.0.2 Developer Preview):*

        - Sync Gateway Dev Ops
      parameters:
      - $ref: '#/parameters/level'
      - $ref: '#/parameters/logLevel'
      - $ref: '#/parameters/logtags'
      responses:
        201:
          description: The operation was successful
  /_sgcollect_info:
    get:
      tags:
      - Server
      summary: Get Sgcollect_info Status
      description: |+
        Will return information about whether sgcollect_info is currently running or not.

        *Sync Gateway Roles Required (CBS 7.0.2 Developer Preview):*

        - Sync Gateway Dev Ops

      responses:
        200:
          description: The operation was successful
          schema:
            $ref: '#/definitions/SGCollectInfoStats'
    post:
      tags:
      - Server
      summary: Start Sgcollect_info
      description: |+
        Starting in Sync Gateway 2.1, sgcollect_info can be triggered using this endpoint.

        *Sync Gateway Roles Required (CBS 7.0.2 Developer Preview):*

        - Sync Gateway Dev Ops

      parameters:
      - $ref: '#/parameters/sgcollect_info'
      responses:
        200:
          description: The request was successful.
    delete:
      tags:
      - Server
      summary: Stop Sgcollect_info
      description: |+
        sgcollect_info can be cancelled using ths endpoint.

        *Sync Gateway Roles Required (CBS 7.0.2 Developer Preview):*

        - Sync Gateway Dev Ops

      parameters:
      - $ref: '#/parameters/sgcollect_info'
      responses:
        200:
          description: The request was successful.
  /_post_upgrade:
    post:
      tags:
      - Server
      summary: Delete Obsolete Design Documents
      description: |+
        Starting in Sync Gateway 2.0, design documents used internally by Sync Gateway will include a version number in their name.



        This version is incremented at each change, but the previous version of the design documents are retained, as they may be required by other nodes.



        Use this `_post_upgrade` endpoint to remove any obsolete design documents when you are sure they are no longer needed.



        *TIP:* Use the `preview=true` query string option to check which design documents will be removed.



        Typical use cases for this end point include:


        - After upgrading Sync Gateway - see ([upgrade guide](upgrade.html#upgrade)).

        - After moving from *non-import-docs* to *import-docs* methods. That is, from `import-docs=False` to `import-docs=True`

        *Sync Gateway Roles Required (CBS 7.0.2 Developer Preview):*

        - Sync Gateway Dev Ops

      parameters:
      - $ref: '#/parameters/upgrade_preview'
      responses:
        200:
          description: The request was successful.

  /_replicate:
    post:
      deprecated: true
      tags:
      - Server
      summary: Start or Cancels Replication
      description: |+
        This API endpoint is now deprecated.
        It is replaced by the Inter-Sync Gateway Replication (v2) replication endpoint

        *About*

        This endpoint is used to start or cancel a database replication operation.

        - Starting a replication with the _replicate endpoint will implicitly set `adhoc=true` for the replication
        - Setting `cancel=true` will set the replication state to **STOPPING**

        *Canceling replications*

        You can cancel continuous replications by adding the cancel field to the JSON request object and setting the value to true.

        Note that the structure of the request must be identical to the original for the cancellation request to be honoured.
        For example, if you requested continuous replication, the cancellation request must also contain the continuous field.

        *Constraints*

        - Use this endpoint only for Inter-Sync Gateway Replication (v1) replications.

      parameters:
      - $ref: '#/parameters/replicate__replication-body'
      responses:
        200:
          description: 200 OK
          schema:
            $ref: '#/definitions/ReplicationResponse'
  /_all_dbs:
    get:
      tags:
      - Server
      summary: Get List of All Databases
      description: |+
        List all databases

        *Sync Gateway Roles Required (CBS 7.0.2 Developer Preview):*

        - Sync Gateway Dev Ops
      responses:
        200:
          description: Identify all available databases
          schema:
            type: array
            items:
              type: object
              $ref: '#/definitions/AllDatabases'
  /_active_tasks:
    get:
      tags:
      - Server
      deprecated: true
      summary: Get List of Active Tasks (v1 replications only)
      description: |+
        *Deprecated @ 2.8*

        Replaced by Inter-Sync Gateway Replication (v2)'s *[_replicationStatus](#/server/get__replicationStatus)* endpoint.
        This **_active_tasks** endpoint is retained **only** for backward compatibility.

        Use this end point to return the status of active Inter-Sync Gateway Replication (v1) replications. Only replications configured on the local node are returned.

        The response is as defined in [_replicationStatus](#/replications/get__db___replicationStatus) except that it also includes:

        - **end_last_seq**, which returns the maximum of (last_seq_pull, last_seq_push)
        - **start_last_seq**, which is not populated (as was the case prior to Sync Gateway 2.8)

        The Inter-Sync Gateway Replication (v2) equivalent is `_replicationStatus?localOnly=true&activeOnly=true` - see [_replicationStatus](#/replications/get__db___replicationStatus).
      responses:
        200:
          description: Information about active replications.
          schema:
            $ref: '#/definitions/ActiveTasks_model'
  /{db}/:
    get:
      operationId: get_database_information
      tags:
      - 'Database Management'
      # title: Get database information
      summary: Get Database Data
      description: |+
        This request retrieves information about the database.

        *Sync Gateway Roles Required (CBS 7.0.2 Developer Preview):*

        - Sync Gateway Dev Ops
      parameters:
      - $ref: '#/parameters/db'
      responses:
        200:
          description: |+
            Request completed successfully.
            The information is returned in the response body.
          schema:
            properties:
              db_name:
                type: string
                title: Database name
                description: Name of the database
              db_uuid:
                type: integer
                description: Database identifier
              disk_format_version:
                type: integer
                description: Database schema version
              disk_size:
                type: integer
                description: Total amount of data stored on the disk (in bytes)
              instance_start_time:
                type: string
                description: Date and time the database was opened (in microseconds since 1 January 1970)
              state:
                type: string
                description: |+
                  The state of the specified database.

                  Possible values are 'Online' and 'Offline'.

                  A database can be taken offline and brought back online using the /{db}/_offline and /{db}/_online endpoints on the Admin REST API.
              update_seq:
                type: string
                description: Number of updates to the database

        401:
          description: |+
            Unauthorized.
            Login required.
        404:
          description: Not Found. Requested database not found.
    post:
      tags:
      - Document
      operationId: create_database_document
      summary: Create Document
      description: |+
        This request creates a new document in the specified database.

        You can either specify the document ID by including the _id in the request message body (the value must be a string), or let the software generate an ID.

        The maximum size allowed for a document is 20MB.

        *Sync Gateway Roles Required (CBS 7.0.2 Developer Preview):*

        - Sync Gateway Application
      parameters:
      - $ref: '#/parameters/db'
      - in: body
        name: body
        description: The document body
        schema:
          type: object
      responses:
        201:
          $ref: '#/responses/200-doc'
    put:
      operationId: create_database
      summary: Create Database
      tags:
      - 'Database Management'
      description: |+
        Use this method to create a new Sync Gateway database.

        The database name is taken from the URL path.
        Pass the required database configuration settings as a JSON object in the request body.

        ```
        {
            "name": "todo_db"
            "bucket": "todo_app"
        }
        ```

        By default the created database is brought online immediately, **unless** you include `"offline": true` in the configuration.

        *Sync Gateway Roles Required (CBS 7.0.2 Developer Preview):*

        - Sync Gateway Architect
      parameters:
        - $ref: '#/parameters/db'
        - $ref: '#/parameters/database_config_body'
      responses:
        201:
          $ref: '#/responses/OK-create'
        401:
          $ref: '#/responses/Unauthorized'

    delete:
      tags:
      - 'Database Management'
      summary: Delete Database
      description: |+
        Delete database

        *Sync Gateway Roles Required (CBS 7.0.2 Developer Preview):*

        - Sync Gateway Architect

      parameters:
      - $ref: '#/parameters/db'
      responses:
        200:
          $ref: '#/responses/200-doc'
  /{db}/_bulk_docs:
    post:
      tags:
      - 'Database Management'
      summary: Add, Update or Delete Bulk Documents
      description: |+
        This request enables you to add, update, or delete multiple documents to a database in a single request. To add new documents, you can either specify the ID (`_id`) or let the software create an ID. To update existing documents, you must provide the document ID, revision identifier (`_rev`), and new document values. To delete existing documents you must provide the document ID, revision identifier, and the deletion flag (`_deleted`).

        The JSON returned by the `_bulk_docs` operation consists of an array of JSON structures, one for each document in the original submission. The returned JSON structure should be examined to ensure that all of the documents submitted in the original request were successfully added to the database.

        *Sync Gateway Roles Required (CBS 7.0.2 Developer Preview):*

        - Sync Gateway Application
      parameters:
      - $ref: '#/parameters/db'
      - $ref: '#/parameters/bulkdocs'
      responses:
        201:
          description: Documents have been created or updated. The response object is an array with the status for each document submitted in the original request.
          schema:
            $ref: '#/definitions/BulkDocsSuccess'
        409:
          description: The operation failed with a forbidden error. Probably because the document already exists in the database but a revision number wasn't specified.
          schema:
            $ref: '#/definitions/Forbidden'
  /{db}/_bulk_get:
    post:
      tags:
      - 'Database Management'
      summary: Get Bulk Documents
      description: |+
        This request returns any number of documents, as individual bodies in a MIME multipart response.

        Each enclosed body contains one requested document.
        The bodies appear in the same order as in the request, but can also be identified by their X-Doc-ID and X-Rev-ID headers.
        - A body for a document with no attachments will have content type application/json and contain the document itself.
        - A body for a document that has attachments will be written as a nested multipart/related body.
        Its first part will be the document's JSON, and the subsequent parts will be the attachments (each identified by a Content-Disposition header giving its attachment name.)

        *Sync Gateway Roles Required (CBS 7.0.2 Developer Preview):*

        - Sync Gateway Application
        - Sync Gateway Application Read Only

      produces:
      - 'multipart/mixed'
      parameters:
      - $ref: '#/parameters/db'
      - $ref: '#/parameters/revs'
      - $ref: '#/parameters/revs_limit'
      - $ref: '#/parameters/include_attachments'
      - $ref: '#/parameters/bulkget'
      responses:
        200:
          description: Request completed successfully
          examples:
            multipart/mixed (document found): |
              --1cba224ff2aa106566e3ab65de9c861c24558ba368f8cd7f6fcde53b88f4
              Content-Type: application/json

              {"_id":"doc123","_rev":"1-c543d6514c609f65180f94af247aaffe","hello":"world!"}
              --1cba224ff2aa106566e3ab65de9c861c24558ba368f8cd7f6fcde53b88f4
            multipart/mixed (document not found): |
              --1cba224ff2aa106566e3ab65de9c861c24558ba368f8cd7f6fcde53b88f4
              Content-Type: application/json; error="true"

              {"error":"not_found","id":"doc1234","reason":"missing","status":404}
              --1cba224ff2aa106566e3ab65de9c861c24558ba368f8cd7f6fcde53b88f4
        301:
          description: Request failed with a forbidden error. This usually happens because the user requesting that document doesn't have access to it. Access to documents is granted to users through channels.
          schema:
            type: object
            properties:
              _id:
                type: string
                description: The document ID that was requested
              _removed:
                type: boolean
                default: true
              _rev:
                type: string
                description: The revision number that was requested
  /{db}/_local/{local_doc}:
    get:
      tags:
      - Document
      summary: Get Specific Local Document
      description: |+
        This request retrieves a local document.

        Local document IDs begin with _local/.
        Local documents are not replicated or indexed, don't support attachments, and don't save revision histories.
        In practice they are almost only used by Couchbase Lite's replicator, as a place to store replication checkpoint data.

        *Sync Gateway Roles Required (CBS 7.0.2 Developer Preview):*

        - Sync Gateway Application
        - Sync Gateway Application Read Only

      parameters:
      - $ref: '#/parameters/db'
      - $ref: '#/parameters/local_doc'
      responses:
        200:
          description: OK

    put:
      tags:
      - Document
      summary: Update Specific Local Document
      description: |+
        This request creates or updates a local document. Local document IDs begin with _local/. Local documents are not replicated or indexed, don't support attachments, and don't save revision histories. In practice they are almost only used by the client's replicator, as a place to store replication checkpoint data.

        *Sync Gateway Roles Required (CBS 7.0.2 Developer Preview):*

        - Sync Gateway Application

      parameters:
      - $ref: '#/parameters/db'
      - $ref: '#/parameters/local_doc'
      responses:
        201:
          $ref: '#/responses/200-doc'
    delete:
      tags:
      - Document
      summary: Delete Specific Local Document
      description: |+
        This request deletes a local document. Local document IDs begin with _local/. Local documents are not replicated or indexed, don't support attachments, and don't save revision histories. In practice they are almost only used by Couchbase Lite's replicator, as a place to store replication checkpoint data.

        *Sync Gateway Roles Required (CBS 7.0.2 Developer Preview):*

        - Sync Gateway Application

      parameters:
      - $ref: '#/parameters/db'
      - $ref: '#/parameters/local_doc'
      - $ref: '#/parameters/rev'
      - $ref: '#/parameters/batch'
      responses:
        200:
          $ref: '#/responses/200-doc'
  /{db}/_changes:
    get:
      tags:
      - 'Database Management'
      summary: Get List of Changes (query parameters)
      description: |+
        This request retrieves a sorted list of changes made to documents in the database, in time order of application.

        Each document appears at most once, ordered by its most recent change, regardless of how many times it's been changed.
        This request can be used to listen for update and modifications to the database for post processing or synchronization.
        A continuously connected changes feed is a reasonable approach for generating a real-time log for most applications.

        *Sync Gateway Roles Required (CBS 7.0.2 Developer Preview):*

        - Sync Gateway Application
        - Sync Gateway Application Read Only

      parameters:
      - $ref: '#/parameters/db'
      - $ref: '#/parameters/limit'
      - $ref: '#/parameters/style'
      - $ref: '#/parameters/active_only'
      - $ref: '#/parameters/include_docs'
      - $ref: '#/parameters/filter'
      - $ref: '#/parameters/channels_list'
      - $ref: '#/parameters/doc_ids'
      - $ref: '#/parameters/feed'
      - $ref: '#/parameters/since'
      - $ref: '#/parameters/heartbeat'
      - $ref: '#/parameters/timeout'
      responses:
        200:
          description: Request completed successfully
          schema:
            $ref: '#/definitions/Changes'
    post:
      tags:
      - 'Database Management'
      summary: Changes
      description: |+
        Same as the GET /_changes request except the parameters are in the JSON body.

        *Sync Gateway Roles Required (CBS 7.0.2 Developer Preview):*

        - Sync Gateway Application
        - Sync Gateway Application Read Only

      parameters:
      - $ref: '#/parameters/db'
      - $ref: '#/parameters/changes_body'

      responses:
        200:
          description: Request completed successfully
          schema:
            $ref: '#/definitions/Changes'

  /{db}/_compact:
    get:
      tags:
      - 'Database Management'
      summary: Get Compact Status
      description: |+
        Use this request to return the current status of a compaction.

        Set the `type` parameter to one of:
        - tombstone - A GET request to /{db}/_compact?type=tombstone returns the number of tombstones removed.
        - attachment - A GET request to /{db}/_compact?type=attachment returns the number of attachments that are removed from the bucket.

        For example:
        ```{
            "status": "running",
            "start_time": "2021-12-02T18:26:17.086152Z",
            "last_error": "",
            "marked_attachments": 0,
            "purged_attachments": 0,
            "compact_id": "68302d2d-2c56-434e-94e0-33c0d0437828",
            "phase": "cleanup"
            }```

      parameters:
      - $ref: '#/parameters/db'
      - $ref: '#/parameters/compaction_type'

      responses:
        200:
          $ref: '#/responses/200-db-compact-get'

    post:
      tags:
      - 'Database Management'

      summary: Compact Database
      description: |+
        Use the ```/{db}/_compact``` endpoint to start a compaction process.
        The process purges the JSON bodies of non-leaf revisions.

        Using this endpoint following a failed compaction will trigger a restart of the compact_id at the appropriate phase (where possible).

        This process is also run periodically by the system.

        Note - Leaf revisions are not purged during compaction.

        Compaction does not remove JSON bodies of leaf nodes (conflicting branches).
        So it is also important to resolve conflicts in your application in order to re-claim disk space.

        *Sync Gateway Roles Required (CBS 7.0.2 Developer Preview):*

        - Sync Gateway Architect

      parameters:
      - $ref: '#/parameters/db'
      - $ref: '#/parameters/compaction_type'
      - $ref: '#/parameters/compaction_action'
      - $ref: '#/parameters/compaction_dry_run'
      - $ref: '#/parameters/compaction_reset'

      responses:
        200:
          $ref: '#/responses/200-db-compact-post-start'
        400:
          $ref: '#/responses/400-db-compact-post-bad-request'
        503:
          $ref: '#/responses/503-db-compact-post-unavailable'

  /{db}/_config:
    get:
      tags:
      - 'Database Configuration'
      summary: Get Database Configuration
      description: |+
        Returns the Sync Gateway configuration of the database specified in the URL. This is a good method to check if a particular key was set correctly on the config file.

        *Sync Gateway Roles Required (CBS 7.0.2 Developer Preview):*

        - Sync Gateway Architect

      parameters:
      - $ref: '#/parameters/db'
      responses:
        200:
          description: Sync Gateway configuration of the running instance.
    put:
      operationId: "update_database_config"
      tags:
      - 'Database Configuration'
      summary: Update Database Configuration
      description: |+
        Use this endpoint to update the configuration of an existing Sync Gateway database.

        Provide the database name in the URL path.
        Provide the required database configuration settings as a JSON object in the request body.

        By default the updated database is brought online immediately, **unless** you include `"offline": true` in the configuration.

        *Sync Gateway Roles Required (CBS 7.0.2 Developer Preview):*

        - Sync Gateway Architect
        - Sync Gateway Application

      parameters:
        - $ref: '#/parameters/db'
        - $ref: '#/parameters/database_config_body'
      responses:
        200:
          $ref: '#/responses/OK'
        401:
          $ref: '#/responses/Unauthorized'
  /{db}/_config/import_filter:
    get:
      operationId: "get_import_filter"
      tags:
      - 'Database Configuration'
      summary: Get Import_Filter Function
      description: |+
        Use this convenience endpoint to get the content of the current `import_filter`

        *Sync Gateway Roles Required (CBS 7.0.2 Developer Preview):*

        - Sync Gateway Architect

      consumes: ['application/javascript']

      parameters:
        - $ref: '#/parameters/db'
      responses:
        200:
          $ref: '#/responses/200-import-filter'
        401:
          $ref: '#/responses/Unauthorized'
    put:
      operationId: "update_import_filter"
      tags:
      - 'Database Configuration'
      summary: Update Import_Filter Function
      description: |+
        Use this convenience endpoint to add or update the `import_filter` Javascript function for an existing Sync Gateway database.

        See the 'Model' below for more info

        *Sync Gateway Roles Required (CBS 7.0.2 Developer Preview):*

        - Sync Gateway Architect

      consumes: ['application/javascript']

      parameters:
        - $ref: '#/parameters/db'
        - $ref: '#/parameters/import_filter_body'
      responses:
        200:
          $ref: '#/responses/200-import-filter'
        401:
          $ref: '#/responses/Unauthorized'
    delete:
      operationId: "delete_import_filter"
      tags:
      - 'Database Configuration'
      summary: Delete Import_Filter Function
      description: |+
        Use this convenience endpoint to remove an existing`import_filter`.

        *Sync Gateway Roles Required (CBS 7.0.2 Developer Preview):*

        - Sync Gateway Architect

      consumes: ['application/javascript']

      parameters:
        - $ref: '#/parameters/db'
      responses:
        200:
          $ref: '#/responses/200-import-filter'
        401:
          $ref: '#/responses/Unauthorized'

  /{db}/_config/sync:
    get:
      operationId: "get_sync_function"
      tags:
      - 'Access Control'
      - 'Database Configuration'
      summary: Get Sync Function
      description: |+
        Get the content of the current Sync Function

        *Sync Gateway Roles Required (CBS 7.0.2 Developer Preview):*

        - Sync Gateway Architect

      consumes: ['application/javascript']
      parameters:
        - $ref: '#/parameters/db'
      responses:
        200:
          $ref: '#/responses/200-sync'
        401:
          $ref: '#/responses/Unauthorized'
    put:
      operationId: "update_sync_function"
      tags:
      - 'Access Control'
      - 'Database Configuration'
      summary: Update Sync Function
      description: |+
        Use this convenience endpoint to add or update the `Sync` function for an existing Sync Gateway database

        See the 'Model' below for more info


        *Sync Gateway Roles Required (CBS 7.0.2 Developer Preview):*

        - Sync Gateway Architect


      consumes: ['application/javascript']
      parameters:
        - $ref: '#/parameters/db'
        - $ref: '#/parameters/sync_function_body'
      responses:
        200:
          $ref: '#/responses/200-sync'
        401:
          $ref: '#/responses/Unauthorized'
    delete:
      operationId: "delete_sync_function"
      tags:
      - 'Access Control'
      - 'Database Configuration'
      summary: Delete Sync Function
      description: |+
        Use this convenience endpoint to remove an existing `Sync` function

        *Sync Gateway Roles Required (CBS 7.0.2 Developer Preview):*

        - Sync Gateway Architect

      consumes: ['application/javascript']
      parameters:
        - $ref: '#/parameters/db'
        - $ref: '#/parameters/sync_function_body'
      responses:
        200:
          $ref: '#/responses/200-sync'
        401:
          $ref: '#/responses/Unauthorized'

  /{db}/{doc}:
    get:
      tags:
      - Document
      parameters:
      - $ref: '#/parameters/db'
      - $ref: '#/parameters/doc'
      - $ref: '#/parameters/rev_get'
      - $ref: '#/parameters/include_attachments'
      - $ref: '#/parameters/atts_since'
      - $ref: '#/parameters/open_revs'
      - $ref: '#/parameters/revs'
      - $ref: '#/parameters/show_exp'
      summary: Get Specific Document
      description:
        This request retrieves a document from a database.

        *Sync Gateway Roles Required (CBS 7.0.2 Developer Preview):*

        - Sync Gateway Application
        - Sync Gateway Application Read Only
      responses:
        200:
          description: The message body contains the following objects in a JSON document.
          schema:
            type: object
    put:
      tags:
      - Document
      parameters:
      - $ref: '#/parameters/db'
      - $ref: '#/parameters/doc'
      - $ref: '#/parameters/new_edits'
      - $ref: '#/parameters/rev_put'
      - in: body
        name: Document
        description: Request body
        schema:
          $ref: '#/definitions/Document_model'
      summary: Create or update document
      description: |+
        This request creates a new document or creates a new revision of an existing document. It enables you to specify the identifier for a new document rather than letting the software create an identifier. If you want to create a new document and let the software create an identifier, use the POST /db request.
        If the document specified by doc does not exist, a new document is created and assigned the identifier specified in doc. If the document already exists, the document is updated with the JSON document in the message body and given a new revision. The maximum size allowed for a document is 20MB.

        Since Sync Gateway 1.3, an expiry property (`_exp`) can also be specified to purge the document after a given time. If **convergence** is enabled (introduced in Sync Gateway 1.5), the behavior of the expiry feature changes in the following way: when the expiry value is reached, instead of getting purged, the **active** revision of the document is tombstoned. If there is another non-tombstoned revision for this document (i.e a conflict) it will become the active revision. The tombstoned revision will be purged when the server's metadata purge interval is reached.

        *Sync Gateway Roles Required (CBS 7.0.2 Developer Preview):*

        - Sync Gateway Application

      responses:
        200:
          $ref: '#/responses/200-doc'
    delete:
      tags:
      - Document
      summary: Delete document
      description: |+
        This request deletes a document from the database.
        When a document is deleted, the revision number is updated so the database can track the deletion in synchronized copies.

        *Sync Gateway Roles Required (CBS 7.0.2 Developer Preview):*

        - Sync Gateway Application

      parameters:
      - $ref: '#/parameters/db'
      - $ref: '#/parameters/doc'
      - $ref: '#/parameters/rev_delete'
      responses:
        200:
          description: OK

  /{db}/{doc}/{attachment}:
    get:
      tags:
      - Document
      summary: Get attachment
      description: |+
        Use this request to get the file attachment associated with a document.
        It returns the raw data of the associated attachment, just as if you were accessing a static file.

        The Content-Type response header is the same content type set when the document attachment was added to the database.

        To remove an attachment from a document, simply update the `_attachments` dictionary of the document in the PUT "/{db}/{id}" request.

        Use the `meta` parameter to request that only the document ID of the attachment blob be returned


        *Sync Gateway Roles Required (CBS 7.0.2 Developer Preview):*

        - Sync Gateway Application
        - Sync Gateway Application Read Only

      parameters:
      - $ref: '#/parameters/db'
      - $ref: '#/parameters/doc'
      - $ref: '#/parameters/attachment'
      - $ref: '#/parameters/rev'
      - in: query
        name: meta
        type: boolean
        description: |+
          If `true` only the document ID of the attachment blob is returned in the response body
        default: false

      responses:
        200:
          description: The message body contains the attachment, in the format specified in the Content-Type header.
          schema:
            type: string
            format: binary
            example: |+
              GET /{db}/{doc}/{attachment}?meta=true
              {
                "content_type": "text/plain",
                "length": 2,
                "key": "_sync:att2:uU0nuZNNPgilLlLX2n2r+sSE7+N6U4DukIj3rOLvzek=:sha1-Kq5sNclPz7QV2+lfQIuc6R7oRu0="
              }

        304:
          description: Not Modified, the attachment wasn't modified if ETag equals the If-None-Match header
        400:
          description: Bad Request - A non boolean value was supplied for the meta parameter.
        404:
          description: Not Found, the specified database, document or attachment was not found.


    put:
      tags:
      - Document
      summary: Add or update a document attachment
      description: |+
        Use this request to add or update the supplied request content as an attachment to the specified document.

        - The maximum content size of an attachment is 20MB.
        - The attachment name must be a URL-encoded string (the file name).
        - You must also supply either the rev query parameter or the If-Match HTTP header for validation, and the Content-Type headers (to set the attachment content type).

        When uploading an attachment using an existing attachment name, the corresponding stored content of the database will be updated. Because you must supply the revision information to add an attachment to the document, this serves as validation to update the existing attachment.

        Uploading an attachment updates the corresponding document revision.
        Revisions are tracked for the parent document, not individual attachments.

        To remove an attachment from a document, simply update the `_attachments` dictionary of the document in the PUT "{db}/{id}" request.

        *Sync Gateway Roles Required (CBS 7.0.2 Developer Preview):*

        - Sync Gateway Application

      parameters:
      - $ref: '#/parameters/db'
      - $ref: '#/parameters/doc'
      - $ref: '#/parameters/attachment'
      - $ref: '#/parameters/rev'
      - in: body
        name: body
        description: The request body
        schema:
          type: string
          format: binary
      - $ref: '#/parameters/content_type'
      responses:
        200:
          description: Operation completed successfully
        409:
          description: Conflict, the document revision wasn't specified or it's not the latest.


  /{db}/_design/{ddoc}:
    get:
      tags:
      - 'Design Documents'
      summary: Get Views of a design document
      description: |+
        Query a design document.

        *Sync Gateway Roles Required (CBS 7.0.2 Developer Preview):*

        - Sync Gateway Application
        - Sync Gateway Application Read Only
      parameters:
      - $ref: '#/parameters/db'
      - $ref: '#/parameters/ddoc'
      responses:
        200:
          description: Views for design document
          schema:
            type: object
            properties:
              my_view_name:
                $ref: '#/definitions/View'
    put:
      tags:
      - 'Design Documents'
      summary: Update views of a design document
      description: |+
        Update views of a design document

        *Sync Gateway Roles Required (CBS 7.0.2 Developer Preview):*

        - Sync Gateway Application
      parameters:
      - $ref: '#/parameters/db'
      - $ref: '#/parameters/ddoc'
      - in: body
        name: body
        description: The request body
        required: false
        schema:
          $ref: '#/definitions/View'
      responses:
        200:
          description: OK
    delete:
      tags:
      - 'Design Documents'
      summary: Delete design document
      description: |+
        Delete a design document.

        *Sync Gateway Roles Required (CBS 7.0.2 Developer Preview):*

        - Sync Gateway Application

      parameters:
      - $ref: '#/parameters/db'
      - $ref: '#/parameters/ddoc'
      responses:
        200:
          description: The status
          schema:
            $ref: '#/definitions/Design'
        default:
          description: Unexpected error
          schema:
            $ref: '#/definitions/Error'

  /{db}/_design/{ddoc}/_view/{view}:
    get:
      tags:
      - 'Design Documents'
      summary: Query a view
      description: |+
        Query a view on a design document.

        *Sync Gateway Roles Required (CBS 7.0.2 Developer Preview):*

        - Sync Gateway Application
        - Sync Gateway Application Read Only

      parameters:
      - $ref: '#/parameters/db'
      - $ref: '#/parameters/ddoc'
      - $ref: '#/parameters/view'
      - in: query
        name: conflicts
        description: Include conflict information in the response. This parameter is ignored if the include_docs parameter is false.
        type: boolean
      - in: query
        name: descending
        description: Return documents in descending order.
        type: boolean
      - in: query
        name: endkey
        description: If this parameter is provided, stop returning records when the specified key is reached.
        type: string
      - in: query
        name: end_key
        description: Alias for the endkey parameter.
        type: string
      - in: query
        name: endkey_docid
        description: If this parameter is provided, stop returning records when the specified document identifier is reached.
        type: string
      - in: query
        name: end_key_doc_id
        description: Alias for the endkey_docid parameter.
        type: string
      - in: query
        name: include_docs
        description: Only works when using Couchbase Server 3.0 and earlier.  Indicates whether to include the full content of the documents in the response.
        type: boolean
      - in: query
        name: inclusive_end
        description: Indicates whether the specified end key should be included in the result.
        type: boolean
      - in: query
        name: group
        description: Group the results using the reduce function to a group or single row.
        type: boolean
      - in: query
        name: group_level
        description: Specify the group level to be used.
        type: integer
      - in: query
        name: key
        description: If this parameter is provided, return only document that match the specified key.
        type: string
      - in: query
        name: limit
        description: If this parameter is provided, return only the specified number of documents.
        type: integer
      - in: query
        name: skip
        description: If this parameter is provided, skip the specified number of documents before starting to return results.
        type: integer
      - in: query
        name: stale
        description: Allow the results from a stale view to be used, without triggering a rebuild of all views within the encompassing design document. Valid values are ok and update_after.
        type: string
      - in: query
        name: startkey
        description: If this parameter is provided, return documents starting with the specified key.
        type: string
      - in: query
        name: start_key
        description: Alias for startkey param.
        type: string
      - in: query
        name: startkey_docid
        description: If this parameter is provided, return documents starting with the specified document identifier.
        type: string
      - in: query
        name: update_seq
        description: Indicates whether to include the update_seq property in the response.
        type: boolean
      responses:
        200:
          description: Query results
          schema:
            $ref: '#/definitions/QueryResult'
  /{db}/_all_docs:
    get:
      tags:
      - 'Database Management'
      summary: All docs
      description: |+
        This request returns a built-in view of all the documents in the database.

        *Sync Gateway Roles Required (CBS 7.0.2 Developer Preview):*

        - Sync Gateway Application
        - Sync Gateway Application Read Only
      parameters:
      - $ref: '#/parameters/db'
      - $ref: '#/parameters/access'
      - $ref: '#/parameters/channels'
      - $ref: '#/parameters/include_docs'
      - $ref: '#/parameters/revs'
      - $ref: '#/parameters/update_seq'
      - $ref: '#/parameters/limit'
      - $ref: '#/parameters/keys'
      - $ref: '#/parameters/startkey'
      - $ref: '#/parameters/endkey'
      responses:
        200:
          description: Query results
          schema:
            $ref: '#/definitions/QueryResult'
    post:
      tags:
      - 'Database Management'
      summary: All docs
      description: |+
        This request retrieves specified documents from the database.

        *Sync Gateway Roles Required (CBS 7.0.2 Developer Preview):*

        - Sync Gateway Application
        - Sync Gateway Application Read Only
      parameters:
      - $ref: '#/parameters/db'
      - $ref: '#/parameters/access'
      - $ref: '#/parameters/channels'
      - $ref: '#/parameters/include_docs'
      - $ref: '#/parameters/revs'
      - $ref: '#/parameters/update_seq'
      - in: body
        name: body
        description: Request body
        schema:
          $ref: '#/definitions/AllDocs'
      responses:
        200:
          description: Query results
          schema:
            $ref: '#/definitions/QueryResult'
  /{db}/_oidc:
    get:
      tags:
      - Authentication
      summary: OpenID Connect Authentication.
      description: |+
        Called by clients to initiate the OIDC Authorization Code flow.
      parameters:
      - $ref: '#/parameters/db'
      - in: query
        name: offline
        description: When true, requests a refresh token from the OP. Sets access_type=offline and prompt=consent on the redirect to the OP. Secure clients should set offline=true and persist the returned refresh token to secure storage.
        type: boolean
        required: false
      - in: query
        name: provider
        description: OpenId Connect provider to be used for authentication, from the list of providers defined in the Sync Gateway Config. If not specified, will attempt to authenticate using the default provider.
        type: string
        required: false
      responses:
        302:
          description: Redirect to the requested OpenID Connect provider for authentication. Redirect link is returned in the Location header.
        400:
          description: Bad request.  Reason is returned as "OpenID Connect not configured for database default".  If a provider was specified in the request, that provider was not defined in the Sync Gateway config.  If no provider was specified, OpenID Connect is not configured in the Sync Gateway config.
        500:
          description: Server Error.  Sync Gateway is unable to connect and validate the OpenID Connect provider requested.
  /{db}/_oidc_callback:
    get:
      tags:
      - Authentication
      summary: OpenID Connect Authentication callback.
      description: |+
        Sync Gateway callback URL that clients are redirected to by the OpenID Connect provider.
      parameters:
      - $ref: '#/parameters/db'
      - in: query
        name: code
        description: OpenID Connect Authorization code.
        type: string
        required: true
      - in: query
        name: provider
        description: OpenId Connect provider to be used for authentication, from the list of providers defined in the Sync Gateway Config. If not specified, will attempt to authenticate using the default provider.
        type: string
        required: false
      responses:
        200:
          description: Successful OpenID Connect authentication.
          schema:
            type: object
            properties:
              id_token:
                type: string
                description: OpenID Connect ID token
              refresh_token:
                type: string
                description: OpenID Connect refresh token
              session_id:
                type: string
                description: Sync Gateway session token
              name:
                type: string
                description: Sync Gateway username
              access_token:
                type: string
                description: OpenID Connect access token
              token_type:
                type: string
                description: OpenID Connect token type
              expires_in:
                type: number
                description: TTL for id_token
        400:
          description: Bad request.
        401:
          description: Authentication failed.  Reason returned in the response body.
  /{db}/_oidc_challenge:
    get:
      tags:
      - Authentication
      summary: OpenID Connect Authentication.
      description: |+
        Called by clients to initiate the OIDC Authorization Code flow.
      parameters:
      - $ref: '#/parameters/db'
      - in: query
        name: offline
        description: When true, requests a refresh token from the OP. Sets access_type=offline and prompt=consent on the redirect to the OP. Secure clients should set offline=true and persist the returned refresh token to secure storage.
        type: boolean
        required: false
      - in: query
        name: provider
        description: OpenId Connect provider to be used for authentication, from the list of providers defined in the Sync Gateway Config. If not specified, will attempt to authenticate using the default provider.
        type: string
        required: false
      responses:
        302:
          description: Redirect to the requested OpenID Connect provider for authentication. Redirect link is returned in the Location header.
        400:
          description: Bad request.  Reason is returned as "OpenID Connect not configured for database default".  If a provider was specified in the request, that provider was not defined in the Sync Gateway config.  If no provider was specified, OpenID Connect is not configured in the Sync Gateway config.
        500:
          description: Server Error.  Sync Gateway is unable to connect and validate the OpenID Connect provider requested.
  /{db}/_oidc_refresh:
    get:
      tags:
      - Authentication
      summary: OpenID Connect refresh.
      description: |+
        Used to obtain a new OpenID Connect ID token based on the provided refresh token.
      parameters:
      - $ref: '#/parameters/db'
      - in: query
        name: refresh_token
        description: OpenID Connect refresh token.
        type: string
        required: true
      - in: query
        name: provider
        description: OpenId Connect provider to be used for authentication, from the list of providers defined in the Sync Gateway Config. If not specified, will attempt to authenticate using the default provider.
        type: string
        required: false
      responses:
        200:
          description: Successful OpenID Connect authentication.
          schema:
            type: object
            properties:
              id_token:
                type: string
                description: OpenID Connect ID token
              session_id:
                type: string
                description: Sync Gateway session token
              name:
                type: string
                description: Sync Gateway username
              access_token:
                type: string
                description: OpenID Connect access token
              token_type:
                type: string
                description: OpenID Connect token type
              expires_in:
                type: number
                description: TTL for id_token
        400:
          description: Bad request.
        401:
          description: Authentication failed.  Unable to refresh token.
  /{db}/_replication:
    post:
      tags:
      - Replication
      summary: Create a new replication definition
      description: |+
        The **_replication** endpoint is used to manage both *ad hoc* and *persistent* replication operations.

        Using a POST request you can insert a new set of replication details.


        **To Cancel a Replication**
        You can cancel continuous replications by adding the cancel field to the JSON request object and setting the value to true.
        Note that the structure of the request must be identical to the original for the cancellation request to be honoured.
        For example, if you requested continuous replication, the cancellation request must also contain the continuous field.

        *Sync Gateway Roles Required (CBS 7.0.2 Developer Preview):*

        - Sync Gateway Replicator

      parameters:
      - $ref: '#/parameters/db'
      - $ref: '#/parameters/replication__replication-body'

      responses:
        200:
          description: Replication successfully updated
          schema:
            $ref: '#/definitions/ReplicationResponse'
        201:
          description: Replication successfully inserted
          schema:
            $ref: '#/definitions/ReplicationResponse'
    get:
      tags:
      - Replication
      summary:
        Get all replication definitions
      description: |+
        Returns an array object containing all replication definitions

        *Sync Gateway Roles Required (CBS 7.0.2 Developer Preview):*

        - Sync Gateway Replicator

      parameters:
      - $ref: '#/parameters/db'

      responses:
        200:
          description: Successful response - returns an array of replication definitions in the body as JSON
          schema:
            $ref: '#/definitions/ReplicationResponseBody'

  /{db}/_replication/{replicationID}:
    get:
      tags:
      - Replication
      summary: Get a replication definition
      description: |+
        Returns requested (**replicationID**) replication definition

        *Sync Gateway Roles Required (CBS 7.0.2 Developer Preview):*

        - Sync Gateway Replicator

      parameters:
      - $ref: '#/parameters/db'
      - $ref: '#/parameters/replication_id-required'
      responses:
        200:
          description: Successful response - returns requested replication definition in the body as JSON
          schema:
            $ref: '#/definitions/ReplicationResponseBody'
    put:
      tags:
      - Replication
      operationId: upsert_replication
      summary: Upsert a replication definition
      description: |+
        The **_replication** endpoint is used to manage both *ad hoc* and *persistent* replication operations.

        Using a PUT request you can update (or insert, if it doesn't exist) a set of replication details.


        **To cancel a replication**
        You can cancel continuous replications by adding the cancel field to the JSON request object and setting the value to true.

        Note that the structure of the request must be identical to the original for the cancellation request to be honoured.

        For example, if you requested continuous replication, the cancellation request must also contain the continuous field.

        *Sync Gateway Roles Required (CBS 7.0.2 Developer Preview):*

        - Sync Gateway Replicator

      parameters:
        - $ref: '#/parameters/db'
        - $ref: '#/parameters/replication_id-upsert'
        - $ref: '#/parameters/replication__replication-body'
      responses:
        200:
          description: Replication successfully updated
          schema:
            $ref: '#/definitions/ReplicationResponse'
        201:
          description: Replication successfully inserted
          schema:
            $ref: '#/definitions/ReplicationResponse'
    delete:
      tags:
      - Replication
      summary: Cancel and delete replication
      description: |+
        Deletes a specific (**replicationID**) replication
        - Removes persisted replication definition
        - Removes all checkpoints associated with the replication
        - Deletes all replication status information associated with the replication

        *Sync Gateway Roles Required (CBS 7.0.2 Developer Preview):*

        - Sync Gateway Replicator

      parameters:
        - $ref: '#/parameters/db'
        - $ref: '#/parameters/replication_id-required'
      responses:
        200:
          description: Replication successfully deleted

  /{db}/_replicationStatus:
    get:
      tags:
        - Replication
      summary: Returns replication status data for  replications matching the criteria
      description: |+
        **About**

        Returns replication status data for all replications matching the criteria specified in the {querystring} parameter.

        **Options**

        The `{queryString}` parameter supports the following filter parameters - see *Parameter* section for more details

          - `activeOnly`
          - `localOnly`
          - `includeConfig`
          - `includeError`

        **Behavior**

        The selection is made from all replications across *all* nodes.

        By default the response includes status data for replications in any state (starting, running, stopped or error) from across all nodes.

          <h5>Example</h5>

          ```
          http://localhost:4985/{db}/_replicationStatus?activeOnly=false&localOnly=false&includeError=true

          ```

        *Sync Gateway Roles Required (CBS 7.0.2 Developer Preview):*

        - Sync Gateway Replicator

      parameters:
      - $ref: '#/parameters/db'
      - in: query
        name: activeOnly
        type: boolean
        default: false
        required: false
        description: |+
          When *true*, only active replications (state=starting, running, stopping) are returned
      - in: query
        name: localOnly
        type: boolean
        default: false
        required: false
        description: |+
          When *true* returns only replications run (or running) the local node since startup.

          By default the response includes replications run or running across all nodes since node start-up.
      - in: query
        name: includeError
        type: boolean
        default: true
        required: false
        description: |+
          When false, omits replications stopped due to error (state=error)

          By default the response includes replications in `error` state.
      - in: query
        name: includeConfig
        type: boolean
        default: false
        required: false
        description: |+
          When *true* the replication definition is included in the response.
      responses:
        200:
          description: Returns information about the active replications
          schema:
            $ref: '#/definitions/ReplicationStatusResponseBody'

  /{db}/_replicationStatus/{replicationID}:
    get:
      tags:
      - Replication
      summary: Returns information on specified replication
      description: |+
        Returns the status of the requested (**replicationID**) replication

        *Sync Gateway Roles Required (CBS 7.0.2 Developer Preview):*

        - Sync Gateway Replicator

      parameters:
        - $ref: '#/parameters/db'
        - $ref: '#/parameters/replication_id-required'
      responses:
        200:
          description: Information about specified replication.
          schema:
            type: object
            $ref: '#/definitions/ReplicationStatusResponseBody'
  # /{db}/_replicationStatus/{replicationID}:
    put:
      tags:
      - Replication
      summary: Modify replication status
      description: |+
        Use this endpoint to change the status of the specified (**replicationID**) replication using the value of the `action` parameter.

        The `action` parameter specifies the status to be set - valid values are

           - `start` - starts a stopped replication

           - `stop` - stops an active replication

           - `reset` - resets a stopped replication (resets checkpoint to zero). For bidirectional replication, both push and pull checkpoints are reset to zero.

           For example

           ```
           http://localhost:4985/fred/_replicationStatus/{replicationID}?action=start
           ```

        *Sync Gateway Roles Required (CBS 7.0.2 Developer Preview):*

        - Sync Gateway Replicator

      parameters:
        - $ref: '#/parameters/db'
        - $ref: '#/parameters/replication_id-required'
        - $ref: '#/parameters/replicationStatus-action'
      responses:
        200:
          description: The required status is successfully set
          schema:
            type: object
            $ref: '#/definitions/ReplicationStatusResponseBody'
  /{db}/_revs_diff:
    post:
      tags:
      - 'Database Management'
      summary: Get Revisions DIff List
      description: |+
        Given a set of document/revision IDs, returns the subset of those that do not correspond to revisions stored in the database.

        *Sync Gateway Roles Required (CBS 7.0.2 Developer Preview):*

        - Sync Gateway Application

      parameters:
      - $ref: '#/parameters/db'
      - in: body
        name: body
        description: Request body
        schema:
          description: A dictionary with document IDs as keys to revision IDs for that document.
          type: array
          items:
            properties:
              key:
                type: string
                description: document id
              value:
                type: string
                description: revision id

      responses:
        200:
          description: |+
            The request was successful.
            Returns a list of revision IDs for that document (the ones that are not stored in the database)
          schema:
            type: array
            items:
              properties:
                key:
                  type: string
                  description: document id
                value:
                  type: string
                  description: revision id

  /{db}/_offline:
    post:
      tags:
      - 'Database Management'
      operationId: take_database_offline
      summary: Take Database Offline
      description: |+
        This request takes the specified database offline.

        An offline database is not accessible through Sync Gateway's Public REST API. However, some commands can be given to Sync Gateway through the Admin REST API.

        Taking a database offline will:

        - Cleanly closes all active `_changes` feeds for this database.
        - Rejects all access to the database through the Public REST API (503 Service Unavailable).
        - Rejects most Admin API requests (503 Service Unavailable). A specific, short list of Admin REST API requests remain available (`GET /{db}`, `PUT /{db}/_config`, `POST /{db}/_resync`).
        - Stops webhook event handlers.
        - Does not take the backing Couchbase Server bucket offline. The bucket remains available and Sync Gateway keeps its connection to the bucket.

        When a database is offline, you can load properties for the database, without stopping and re-starting the Sync Gateway instance. The new properties are applied when the database is brought online.

        Taking a database offline that is in the progress of coming online will take the database offline after it comes online.

        For more information about taking a database offline and bringing it back online, see [this guide](database-offline.html).


        *Sync Gateway Roles Required (CBS 7.0.2 Developer Preview):*

        - Sync Gateway Architect
      parameters:
      - $ref: '#/parameters/db'
      responses:
        200:
          description: Database brought online
  /{db}/_online:
    post:
      tags:
      - 'Database Management'
      summary: Bring Database Online.
      description: |+
        When a database is online, Sync Gateway serves both Public and Admin REST API requests for the database. This request brings the specified database online, either immediately or after a specified delay.

        Bringing a database online:

        - Closes the databases connection to the backing Couchbase Server bucket.
        - Reloads the database configuration, and connects to the backing Couchbase Server bucket.
        - Re-establishes access to the database from the Public REST API.
        - Accepts all Admin API requests.

        You can bring an offline database online after a specific delay. Uses for this include:

        - Making a database available for Couchbase Mobile clients at a specific time.
        - Making databases on several Sync Gateway instances available at the same time.

        For more information about taking a database offline and bringing it back online, see [this guide](database-offline.html).

        *Sync Gateway Roles Required (CBS 7.0.2 Developer Preview):*

        - Sync Gateway Architect
      parameters:
      - $ref: '#/parameters/db'
      - in: body
        name: body
        description: Optional request body to specify a delay.
        required: false
        schema:
          type: object
          properties:
            delay:
              type: integer
              description: Delay in seconds before bringing the database online.
      responses:
        200:
          description: OK - online request accepted.
        503:
          description: Service Unavailable - Database resync is in progress.
  /{db}/_purge:
    post:
      tags:
      - Document
      summary: Purge document
      description: |+
        The purge command provides a way to remove a document from the bucket itself. The operation removes all the revisions (active and tombstones) for the specified document(s). A common usage of this endpoint is to remove tombstone documents that are no longer needed, thus recovering storage space and reducing data replicated to clients. Other clients are not notified when a revision has been purged; so in order to purge a revision from the system it must be done from all databases (on Couchbase Lite and Sync Gateway).

        When **convergence** is enabled (introduced in Sync Gateway 1.5), this endpoint removes the document and its associated extended attributes.


        *Sync Gateway Roles Required (CBS 7.0.2 Developer Preview):*

        - Sync Gateway Application
      parameters:
      - $ref: '#/parameters/db'
      - in: body
        name: body
        description: The message body is a JSON document that contains the following objects.
        schema:
          $ref: '#/definitions/PurgeBody'
      responses:
        200:
          description: OK - The purge operation was successful
          schema:
            type: array
            description: |+
              Response object, contains one property for each document ID successfully purged, the property key is the "docID" and the property value is a list containing the single entry "*".
            items:
              type: string
              description: Revision ID that was purged
  /{db}/_raw/{doc}:
    get:
      tags:
      - Document
      summary: Document with metadata
      description: |+
        Returns the document with the metadata.

        Note: The direct use of this endpoint is unsupported. The sync metadata is maintained internally by Sync Gateway and its structure can change. It should not be used to drive business logic of applications since the response to the `/{db}/_raw/{id}` endpoint can change at any time.\

        *Sync Gateway Roles Required (CBS 7.0.2 Developer Preview):*

        - Sync Gateway Application
        - Sync Gateway Application Read Only
      parameters:
      - $ref: '#/parameters/db'
      - $ref: '#/parameters/doc'
      responses:
        200:
          description: OK
          schema:
            $ref: '#/definitions/DocMetadata'

  /{db}/_resync:
    get:
      tags:
      - 'Database Management'
      summary: Show resync status
      description: |+
        This request returns the status of the asynchronous `_resync` operation, including:

        - status
        - docs processed
        - docs changed
        - last error (if any)

        **Sync Gateway Roles Required:**

        - Sync Gateway Architect
      parameters:
      - $ref: '#/parameters/db'
      responses:
        200:
          $ref: '#/responses/200-resync'

    post:
      tags:
      - 'Database Management'
      summary: Start or Stop Resync
      description: |+

        Use the _resync operation whenever you have modified the database's sync function such that the channel or access mappings for any existing document would change as a result.

        The request will start or stop the _resync process depending upon the ```action``` parameter provided.
        If no ```action``` parameter is given then `start` is assumed.

        **```action=start```**

        The start action causes all documents to be reprocessed by the database's sync function.
        This is an **asynchronous** operation.

        When the sync function is invoked by `_resync`, the requireUser() and requireRole() calls will always return 'true'.

        A _resync operation on a database that is not in the offline state will be rejected (503 Service Unavailable).

        **```action=stop```**

        The currently running resync operation is stopped.


        **```regenerate_sequences=true```**
        **Use this only when requested to do so by the Couchbase support team**

        This request will start a resync while regenerating sequences.

        The resync action is carried out **only** on the node that the POST is made to.
        It is not cross-node aware.

        In a multi-node cluster, the resync must be only run on one node.
        Users should bring other nodes offline before initiating this action.
        Starting it on more than one node will result in multiple resyncs running, with undefined system behavior.

        *Sync Gateway Roles Required (CBS 7.0.2 Developer Preview):*

        - Sync Gateway Architect

      parameters:
      - $ref: '#/parameters/db'
      - $ref: '#/parameters/resync-action'
      - $ref: '#/parameters/resync-regenerate'

      responses:
        200:
          $ref: '#/responses/200-resync'
        400:
          $ref: '#/responses/400-resync-post-stopped'
        503:
          $ref: '#/responses/503-resync-post'


  /{db}/_revtree/{doc}:
    get:
      produces:
      - text/plain
      tags:
      - Document
      summary: Revision Tree structure in Graphviz Dot format | not officially supported
      description: |+
        Returns the dot syntax of the revision tree which can be rendered into a PNG image with the [CLI dot tool](http://www.graphviz.org/).

        - Install the dot tool via `brew install graphviz`.
        - Save the response text to a file (for example, **revtree.dot**).
        - Render a PNG by calling `dot -Tpng revtree.dot > revtree.png`.

        **Note:** This endpoint is useful for debugging purposes only. It is not officially supported.

        *Sync Gateway Roles Required (CBS 7.0.2 Developer Preview):*

        - Sync Gateway Application
        - Sync Gateway Application Read Only
      parameters:
      - $ref: '#/parameters/db'
      - $ref: '#/parameters/doc'
      responses:
        200:
          description: Success and returns the revtree as plain text.
  /{db}/_role:
    get:
      tags:
      - 'Database Security'
      summary: Get All Roles
      description: |+
        This request returns all the roles in the specified database.

        *Sync Gateway Roles Required (CBS 7.0.2 Developer Preview):*

        - Sync Gateway Architect
        - Sync Gateway Application
        - Sync Gateway Application Read Only
      parameters:
      - $ref: '#/parameters/db'

      responses:
        200:
          description: |+
            200 OK - Returns the list of roles as an array of strings

            The message body contains the list of roles in a JSON array. Each element of the array is a string representing the name of a role in the specified database.
          schema:
            type: array
            items:
              description: ""
              type: string
        401:
          $ref: '#/responses/Unauthorized'

    post:
      tags:
      - 'Database Security'
      summary: Create New Role
      description: |+
        This request creates a new role

        *Sync Gateway Roles Required (CBS 7.0.2 Developer Preview):*

        - Sync Gateway Architect
        - Sync Gateway Application
      parameters:
      - $ref: '#/parameters/db'
      - $ref: '#/parameters/role_body'
      responses:
        201:
          $ref: '#/responses/OK-create'
        401:
          $ref: '#/responses/Unauthorized'
        409:
          $ref: '#/responses/Conflict'
  /{db}/_role/{name}:
    get:
      tags:
      - 'Database Security'
      summary: Get Specific Role
      description: |+
        Request a specific role by name.

        *Sync Gateway Roles Required (CBS 7.0.2 Developer Preview):*

        - Sync Gateway Architect
        - Sync Gateway Application
        - Sync Gateway Application Read Only

        Without `Application` or `Application Read Only` users will be unable to see dynamic user or role data.
      parameters:
      - $ref: '#/parameters/db'
      - $ref: '#/parameters/role_name'
      responses:
        200:
          description: The response contains information about this role.
          schema:
            type: object
            properties:
              name:
                type: string
              admin_channels:
                type: array
                description: |+
                    The admin channels that this role has granted access to. Admin channels are the ones which are
                    granted access to in the config file or via the Admin REST API.
                items:
                  type: string
              all_channels:
                type: array
                description: All the channels that this role has access to.
                items:
                  type: string
        401:
          $ref: '#/responses/Unauthorized'

    put:
      operationId: "upsert_role"
      tags:
      - 'Database Security'
      summary: Update Specific Role
      description: |+
        Use this convenience endpoint to upsert a Sync Gateway role.

        *Sync Gateway Roles Required (CBS 7.0.2 Developer Preview):*

        - Sync Gateway Architect
        - Sync Gateway Application
      parameters:
      - $ref: '#/parameters/db'
      - $ref: '#/parameters/role_name'
      - $ref: '#/parameters/role_body'
      responses:
        200:
          $ref: '#/responses/OK'
        201:
          $ref: '#/responses/OK-create'
        401:
          $ref: '#/responses/Unauthorized'
    delete:
      tags:
      - 'Database Security'
      summary: Delete Specific Role
      description: |+
        This request deletes the role with the specified name.

        *Sync Gateway Roles Required (CBS 7.0.2 Developer Preview):*

        - Sync Gateway Architect
        - Sync Gateway Application

      parameters:
      - $ref: '#/parameters/db'
      - $ref: '#/parameters/role_name'
      responses:
        200:
          description: 200 OK - The role was successfully deleted
  /{db}/_session:
    post:
      tags:
      - Session
      summary: Create New Session
      description: |+
        If the credentials provided in the request body are valid, the session is created with an idle session timeout of 24 hours.
        An idle session timeout in the context of Sync Gateway is defined as the following:
        - If 10% or more of the current expiration time has elapsed when a subsequent request with that session id is processed, the session's expiry time is automatically updated to 24 hours from that time.

        *Sync Gateway Roles Required (CBS 7.0.2 Developer Preview):*

        - Sync Gateway Architect
        - Sync Gateway Application

      parameters:
      - $ref: '#/parameters/db'
      - in: body
        name: SessionBody
        description: The message body is a JSON document that contains the following objects.
        schema:
          type: object
          properties:
            name:
              type: string
              description: Username of the user the session will be associated to.
            ttl:
              description: |+
                Default is 24 hours (86400 seconds).
                The TTL (time-to-live) of the session, in seconds.
                The value must be greater than 0.
              type: integer
              default: 86400
              example: 180
      responses:
        200:
          description: Session successfully created.
          schema:
            type: object
            properties:
              cookie_name:
                type: string
                description: Cookie used for session handling
              expires:
                type: string
                description: Expiration time for session.
              session_id:
                type: string
                description: Session ID.
  /{db}/_session/{sessionid}:
    get:
      tags:
      - Session
      summary: Get Session Data
      description: |+
        This request retrieves information about a session.

        *Sync Gateway Roles Required (CBS 7.0.2 Developer Preview):*

        - Sync Gateway Architect
        - Sync Gateway Application
        - Sync Gateway Application Read Only
      parameters:
      - $ref: '#/parameters/db'
      - $ref: '#/parameters/sessionid'
      responses:
        200:
          description: 200 OK - Request completed successfully.
          schema:
            type: object
            properties:
              authentication_handlers:
                type: array
                items:
                  type: object
                  description: List of supported authentication handlers
              ok:
                type: boolean
                description: Success flag
              userCtx:
                type: object
                description: Contains an object with properties channels (the list of channels for the user associated with the session) and name (the user associated with the session)
    delete:
      tags:
      - Session
      summary: Delete Specific Session
      description: |+
        This request deletes a single session.

        *Sync Gateway Roles Required (CBS 7.0.2 Developer Preview):*

        - Sync Gateway Architect
        - Sync Gateway Application
      parameters:
      - $ref: '#/parameters/db'
      - $ref: '#/parameters/sessionid'
      responses:
        200:
          description: |+
            200 OK - Request completed successfully.

            If the session is successfully deleted, the response has an empty message body.
            If the session is not deleted, the message body contains error information.
  /{db}/_user/{name}/_session:
    delete:
      tags:
      - Session
      summary: Delete All User Sessions
      description: |+
        This request delete the session for the specified user.

        *Sync Gateway Roles Required (CBS 7.0.2 Developer Preview):*

        - Sync Gateway Architect
        - Sync Gateway Application
      parameters:
      - $ref: '#/parameters/db'
      - $ref: '#/parameters/name'
      responses:
        200:
          description: User session deleted.
  /{db}/_user/{name}/_session/{sessionid}:
    delete:
      tags:
      - Session
      summary: Delete Specific User Session
      description: |+
        This request delete the specified session for the specified user.

        *Sync Gateway Roles Required (CBS 7.0.2 Developer Preview):*

        - Sync Gateway Architect
        - Sync Gateway Application
      parameters:
      - $ref: '#/parameters/db'
      - $ref: '#/parameters/name'
      - $ref: '#/parameters/sessionid'
      responses:
        200:
          description: User session deleted.
  /{db}/_user/:
    get:
      tags:
      - 'Database Security'
      summary: Get All Users
      description: |+
        This request returns a list of all users

        *Sync Gateway Roles Required (CBS 7.0.2 Developer Preview):*

        - Sync Gateway Architect
        - Sync Gateway Application
        - Sync Gateway Application Read Only
      parameters:
      - $ref: '#/parameters/db'
      responses:
        200:
          description:  |+
            The message body contains the list of users in a JSON array.
            Each element of the array is a string representing the name of a user in the specified database.
          schema:
            type: array
            items:
              type: string
              description: username
        404:
          $ref: '#/responses/NotFound'
    post:
      tags:
      - 'Database Security'
      summary: Create New User
      description: |+
        This request creates a new user

        *Sync Gateway Roles Required (CBS 7.0.2 Developer Preview):*

        - Sync Gateway Architect
        - Sync Gateway Application`
      parameters:
      - $ref: '#/parameters/db'
      - $ref: '#/parameters/user_body'
      responses:

        201:
          $ref: '#/responses/OK-create'
        401:
          $ref: '#/responses/Unauthorized'
        409:
          $ref: '#/responses/Conflict'
  /{db}/_user/{name}:
    get:
      tags:
      - 'Database Security'
      summary: Get User Data
      description: |+
        This request returns information about the specified user.

        *Sync Gateway Roles Required (CBS 7.0.2 Developer Preview):*

        - Sync Gateway Architect
        - Sync Gateway Application
        - Sync Gateway Application Read Only

        Without `Application` or `Application Read Only` users will be unable to see dynamic user or role data.
      parameters:
      - $ref: '#/parameters/db'
      - $ref: '#/parameters/name'

      responses:
        200:
          $ref: '#/responses/200-User'
        401:
          $ref: '#/responses/Unauthorized'

    put:
      operationId: "upsert_user"
      tags:
      - 'Database Security'
      summary: Update User Data
      description: |+
        Use this method to create or update a user

        *Sync Gateway Roles Required (CBS 7.0.2 Developer Preview):*

        - Sync Gateway Architect
        - Sync Gateway Application
      parameters:
      - $ref: '#/parameters/db'
      - $ref: '#/parameters/name'
      - $ref: '#/parameters/user_body'
      responses:
        200:
          $ref: '#/responses/OK'
        201:
          $ref: '#/responses/OK-create'
        401:
          $ref: '#/responses/Unauthorized'

    delete:
      tags:
      - 'Database Security'
      summary: Delete Specific User
      description: |+
        This request deletes the user with the specified name

        *Sync Gateway Roles Required (CBS 7.0.2 Developer Preview):*

        - Sync Gateway Architect
        - Sync Gateway Application
      parameters:
      - $ref: '#/parameters/db'
      - $ref: '#/parameters/name'
      responses:
        200:
          $ref: '#/responses/OK'
        401:
          $ref: '#/responses/Unauthorized'


responses:
  200-doc:
    description: Operation completed successfully
    schema:
      $ref: '#/definitions/doc-resp'

  200_startup_config:
    description: Sync Gateway configuration of the running instance.
    schema:
      $ref: '#/definitions/Bootstrap_model'

  200-db-compact-get:
    description: |+
      OK - A successful response will return a JSON object containing the _compact status.

      The current phase of `running` compact processes is returned in `phase`.

    schema:
      $ref: '#/definitions/Compact_Response'
      example:
        {
          "status": "running",
          "start_time": "2021-12-02T18:26:17.086152Z",
          "last_error": "",
          "marked_attachments": 0,
          "purged_attachments": 0,
          "compact_id": "68302d2d-2c56-434e-94e0-33c0d0437828",
          "phase": "cleanup"
        }

  200-db-compact-post-start:
    description: |
      OK - This successful response indicates _compact process was started.
      The response body comprises a JSON object showing the _compact status.
    schema:
      $ref: '#/definitions/Compact_Response'
      example:
        {
          "id": "2",
          "status": "Started",
          "start_time": "2015-09-23T17:27:17.55+01:00",
          "duration": "0ms",
          "atts_compacted": 0
        }

  400-db-compact-post-bad-request:
    description: |+
      Bad Request

        This can mean that a required parameter has not been provided, the value supplied is invalid, or the combination of provided parameters is invalid.

        Compaction API returns a 400 Bad Request error in the following cases:
          - A GET /{db}/_compact request is submitted with an invalid value for type parameter (anything other than tombstone or attachment).
          - A POST /{db}/_compact request is submitted with an invalid value for type parameter (type must be either tombstone or attachment) and or action parameter (action must be either start or stop).

  503-db-compact-post-unavailable:
    description: |+
      Service Unavailable

      A 503 Service Unavailable error indicates that the system is not ready to handle the submitted compaction start request due another compaction is running.
      You may encounter this error when you submit a compaction request in the middle of another.

  200-import-filter:
    description: OK
    schema:
      $ref: '#/definitions/Import_filter_model'

  200-sync:
    description: OK
    schema:
      $ref: '#/definitions/Sync_model'

  200-User:
    description: 200 OK - Returns information about the specified user
    schema:
      $ref: '#/definitions/User-response'
      example:
        {
          "name": "jim",
          "admin_channels" : [
            "!",
            "jim.roberts@gmail,com"
          ],
          "all-Channels": [
            "!",
            "jim. roberts@gmail,com"
          ],
          "email": "jim.roberts@gmail.com"
        }

  200-resync:
    description: OK
    schema:
      $ref: '#/definitions/Resync-response'
      example:
        {
          "status": "completed",
          "start_time": "2022-01-05T15:05:27.521824Z",
          "last_error": "",
          "docs_changed": 0,
          "docs_processed": 0
        }

  400-resync-post-stopped:
    description: 400 - Database _resync not running

  503-resync-post:
    description: |+
      503 error code. The meaning varies depending on the action parameter:

      - action=start - Database must be offline before calling _resync.
      - action=stop - Database _resync already in progress

  OK:
    description: 200 - OK - Operation successful

  OK-create:
    description: 201 - OK - Create Operation successful

  Unauthorized:
    description: 401 - Unauthorized - Error validating credentials

  NotFound:
    description: 404 - Not Found - Object missing or misreferenced

  Conflict:
    description: 409 - Conflict - For example, an object with this name already exists


definitions:

  Bootstrap_model:
    type: object
    title: Bootstrap Configuration Model
    description: |+
      Sync Gateway's start-up configuration properties
    properties:

      bootstrap:
        type: object
        title: Bootstrap configuration
        description: Define fundamental bootstrap related configuration properties
        properties:
          group_id:
            type: string
            default: "default"
            description: |+
              The ID of the configuration group to which this node belongs.

          config_update_frequency:
            type: string
            default: "10s"
            description: |+
              Sets the interval between checks for new or updated configurations made by other nodes in Couchbase Server

              It is provided as string, which uses Go's duration format (e.g: 1s = 1 second, 5m = 5 minutes , 1h32m15s = 1 hour, 32 mins, 15 seconds)
              see: https://pkg.go.dev/time#ParseDuration

          server:
            type: string
            default: none
            description: |+
              Sets the endpoint for the Couchbase Server holding (database) configuration details.

              The value of the *server* property specifies the Hostname(s) to the Couchbase Server node(s) in the cluster.

              Sync Gateway supports the ability to specify multiple hosts in the configuration.
              Sync Gateway supports both the `couchbase://` and `http://` schemes for specifying connection endpoints.

              Sync Gateway also supports *SSL* in the connection to Couchbase Server; use the `couchbases://` scheme for this.
              As with the Couchbase Server SDKs, the `https://` scheme is **not** supported.

              Examples of valid `server` values for *IPv4* include:
              - `couchbase://host1`
              - `couchbases://host1`
              - `couchbase://host1,host2`
              - `couchbase://host1:11210,host2,`
              - `couchbases://host1:11207,host2`
              - `http://host1:8091`
              - `http://host1,host2:8091`
              - `http://foo:bar@host1:8091`

              Examples of valid `server` values for *IPv6* include:
              - `http://[2001:db8::8811]:8091` *// single node IPv6 - http scheme with default server port*
              - `couchbases://[2001:db8::8811]` *// single node SSL IPv6 - default port (omitted)*
              - `couchbase://[2001:db8::8811],[2001:db8::8822]:888` *// node1 default port, node2 port 888*

              As with the SDK, when using the `couchbase://` or `couchbases://` schemes, the port is not required, but if specified should be the external/internal bucket ports (defaults are 11210 or 11207 respectively). Attempting to use the admin ports (8091/18091) will result in a startup error.

              **Alternate Addresses**

              On startup, Sync Gateway will try each hostname that is provided until it is able to connect successfully.

              By default, if a remote cluster has an external address set, then when SG connects it will apply a heuristic to determine whether to choose between external or default (internal) addresses.

              The choice is based on the host names supplied in the connection string.
              - SG uses external networking only when none of the supplied host names match any of Couchbase Server's internal node addresses, and an external address is defined.
              - In all other cases Sync Gateway uses the default (internal) networking.

              However, it is possible to override this behavior by adding a `network` parameter to the connection string.

              The `network` parameter can be --
              - auto - this is the default value if no parameter is provided. In this case the heuristic described above is applied to determine the address used; so effectively there is no override.
              - external - to always force use of the external address
              - default - to always force use of the internal address

              For example:
              ```"server": "couchbases://my-cbs-server?network=default"```

              Will force the connection to ignore any alternative external addresses configured on the Couchbase Server node.

              **Lost Connections**

              If the connection to Couchbase Server is lost during normal operations, Sync Gateway will automatically re-connect to another node in the cluster. During that re-connection period, the Sync Gateway will appear offline - see [Taking Databases Offline](database-offline.html) - and documents will not be replicated to mobile clients.

          username:
            type: string
            default: none
            description: |+
              The username to be used when authenticating to the server.

          password:
            type: string
            default: none
            description: |+
              The password to be used when authenticating to the server.


          ca_cert_path:
            type: string
            title: Root CA cert path for TLS connection
            description: |+
              Absolute or relative path on the filesystem to the root CA certificate to verify the certificate chain and hostname of the Couchbase Server cluster.

              Works in conjunction with `server_tls_skip_verify` to control whether system root pool is used or not.
              Set this empty and `server_tls_skip_verify` true to avoid using system root pool

          server_tls_skip_verify:
            type: boolean
            description:
              Defaults to `false`, which requires a valid CA Cert Path.

              Works in conjunction with `ca_cert_path` to control whether system root pool is used or not.

              Set this true and `ca_cert_path` empty to allow, for example, self-signed or un-trusted certificates.
              This will be the default of-of-the-box setting.

          x509_cert_path:
            type: string
            title: Cert path (public key) for X.509 bucket auth
            description: |+
              Use x509_cert_path to define the absolute or relative path on the filesystem to the x509 certificate.

              Relative paths are relative to the directory containing the Sync Gateway executable.

          x509_key_path:
            type: string
            title: Key path (private key) for X.509 bucket auth
            description: |+
              Absolute or relative path on the filesystem to the X509 key.

              Relative paths are relative to the directory containing the Sync Gateway executable.

          use_tls_server:
            type: boolean
            default: true
            description: |+
              Default to `true`, which forces the connection to Couchbase Server to use TLS.

              Use `use_tls_server` to enforce use of a secure scheme (for example, `couchbases://`) to connect to Couchbase Server.

              Set this `false` to use a non-secure scheme (for example with `couchbase://`).

              If the scheme used does not match that indicated by the `use_tls_server` value (for example, `couchbases://` with `use_tls_server` = `false`) then Sync Gateway will error and refuse to start.

          kv_tls_port:
            type: integer
            default: 11207
            description: |+
              Optional value for the Memcached TLS port, if not using the  default (11207)

          max_concurrent_query_ops:
            description: |+
              Sets the maximum number of concurrent query operations allowed
            type: integer
            default: 1000

      api:
        type: object
        title:
          API configuration
        description: Define API related configuration properties
        properties:
          admin_interface:
            type: string
            default: '127.0.0.1:4985'
            description: |+
              Port or TCP network address (IP address and the port) that the Admin REST API listens on.

              The loopback address prefix before the port (`127.0.0.1`) means the interface will not be reachable from other hosts. To make it reachable, change it to ":4985".

              Change requires restart of Admin API
          admin_interface_authentication:
            type: boolean
            default: true
            description: |+
              Use the `admin_interface_authentication` property to disable authentication for the metrics API.
              This option should be used with discretion and only in test environments.

              By default the Admin API requires Couchbase Server RBAC authentication.
              The user must provide credentials to an existing user with an appropriate Sync Gateway role.

          metrics_interface:
            type: string
            default: '127.0.0.1:4986'
            description: |+
              This defines the Port or TCP network address (IP address and the port) that the Metrics REST API will listen on.

              Using the loopback address prefix before the port (`127.0.0.1`) means the interface will not be reachable from other hosts.

              For example
              ```"metricsInterface": "127.0.0.1:4986"```
          metrics_interface_authentication:
            type: boolean
            default: true
            description: |+
              Use the `metrics_interface_authentication` property to disable authentication for the metrics API.
              This option should be used with discretion and only in test environments.

              By default the Metrics API requires Couchbase Server RBAC authentication.
              The user must provide credentials to an existing user with an appropriate Sync Gateway role.

          profile_interface:
            type: string
            description: |+
              TCP network address (IP address and the port) that the Go profile API listens on.
              You can obtain Go profiling information from the interface.
              You can omit the IP address.

          public_interface:
            type: string
            default: ':4984'
            description: |+
              Public REST API port

              Change requires restart of Public API

          compress_responses:
            description: |+
              Whether to compress HTTP responses. Set to false to disable compression of HTTP responses.

            type: boolean
            default: true
          cors:
            type: object
            description: |+
              Configuration object for allowing cross-origin resource sharing (CORS).
              This is useful to interact directly with Sync Gateway from HTML 5 applications via XHR.

              Change requires HTTP server restart
            properties:
              headers:
                type: array
                description: |+
                  List of HTTP headers that can be used by domains specified in the `origin` and `login_origin` properties.

                  A common value is `["Content-Type"]` as clients use the `Content-Type: application/json` header when sending data as JSON in the body of POST/PUT requests.

                  Change requires HTTP server restart
                items:
                  type: string
              login_origin:
                type: array
                description: |+
                  List of allowed login origins.

                  Change requires HTTP server restart

                items:
                  type: string
              max_age:
                type: integer
                description: |+
                  Value for the Access-Control-Max-Age header.
                  This is the period of time, in seconds, that the response to a CORS preflight request is cached before sending another preflight request.

                  Change requires HTTP server restart

              origin:
                type: array
                description: |+
                  List of allowed origins; use a wildcard character (*) to allow access from everywhere.

                  **Note** that the wildcard (*) cannot be used if you plan to authenticate users as well (by using the `withCredentials` flag on the client side).
                  Instead specify the explicit domain(s) in the `origin` and `login_origin` properties of the configuration file.

                  Change requires HTTP server restart
                items:
                  type: string
                  description: An allowed origin array element

          hide_product_version:
            type: boolean
            default: false
            description: |+
              Determines whether product versions are removed from Server headers and REST API responses.
              This setting does not apply to the Admin REST API.

              This customization of the Sync Gateway response avoids revealing the version of the Sync Gateway to HTTP requests to the root path.

          https:
            type: object
            description: Group in which to specify any API HTTPS configuration properties
            properties:

              tls_minimum_version:
                type: string
                default: 'tlsv1.2'
                title: The minimum allowable TLS version for the REST APIs
                description: |+
                  Enforce a minimum TLS version to be used in replications with Couchbase Lite.

                  Possible values are:

                  - "tlsv1"

                  - "tlsv1.1"

                  - "tlsv1.2"

                  - "tlsv1.3"

                  Change requires HTTP server restart

              tls_cert_path:
                type: string
                title: The TLS certificate file to use for the REST APIs
                description: |+
                  Absolute or relative path on the filesystem to the TLS certificate file, if TLS is used to secure Sync Gateway connections

                  To use plaintext, omit both this property and the `tls_key_path` property.

                  A relative path is from the directory that contains the Sync Gateway executable file.

                  Change requires HTTP server restart
              tls_key_path:
                type: string
                title: The TLS key file to use for the REST APIs
                description: |+
                  Absolute or relative path on the filesystem to the TLS private key files.

                  To use plaintext, omit both this property and the `tls_cert_path` property.

                  A relative path is from the directory that contains the Sync Gateway executable file.

                  Change requires HTTP server restart
          idle_timeout:
            type: integer
            default: 90
            description: |+
              Maximum duration (in seconds) to wait for the next request when keep-alives are enabled

              Change requires HTTP server restart
          max_connections:
            type: integer
            default: 0
            description: |+
              Maximum number of incoming HTTP connections to accept.

              Change requires HTTP server restart
          pretty:
            type: boolean
            default: false
            description: |+
              (**Deprecated**) Whether to pretty-print JSON responses.

          read_header_timeout:
            type: integer
            default: 5
            description: |+
              Maximum duration (in seconds) allowed to read request headers

              Change requires HTTP server restart
          server_read_timeout:
            type: integer
            description: |+
              Maximum duration in seconds before timing out the read of an HTTP(S) request.

              This property only effects the HTTP connections on the Sync Gateway public and admin ports.

              Sync Gateway is written in the Go programming language, therefore the value set in the configuration file is passed to Go's server instance [https://golang.org/pkg/net/http/#Server](https://golang.org/pkg/net/http/#Server).

              Change requires HTTP server restart
          server_write_timeout:
            type: integer
            description: |+
              Maximum duration in seconds before timing out the write of an HTTP(S) response.

              This property only effects the HTTP connections on the Sync Gateway public and admin ports.

              Sync Gateway is written in the Go programming language, therefore the value set in the configuration file is passed to Go's server instance [https://golang.org/pkg/net/http/#Server](https://golang.org/pkg/net/http/#Server).

              Change requires HTTP server restart

      logging:
        description: Define logging configuration
        $ref: '#/definitions/Logging_model'

      replicator:
        title:
          Replicator configuration
        description: Define Replicator related configuration properties
        properties:
          blip_compression:
            type: integer
            default: 6
            description: |+
              This sets the 'deflate' compression level to use when compressing messages sent via the WebSocket protocol, where:

              - 0 means no compression,
              - 1 means fastest (least) compression
              - 9 means slowest (most) compression.
          max_heartbeat:
            type: integer
            default: 0
            description: |+
              This specifies the Maximum Heartbeat value for the ```_changes feed``` requests; the time in second between heartbeats.
              - The default value of ```maxHeartbeat``` is 0 (zero)
              - The minimum value of ```maxHeartbeat``` is 25 (25,000 ms)

      auth:
        type: object
        title: Auth configuration
        description: Define Auth related configuration properties
        properties:
          bcrypt_cost:
            type: integer
            default: 10
            description: Cost to use for bcrypt password hashes

      unsupported:
        type: object
        title: Unsupported configuration
        description: Collection of unsupported properties
        properties:
          stats_log_freq:
            type: string
            default: "1m"
            description:  |+
              It is provided as string, which uses Go's duration format (e.g: 1s = 1 second, 5m = 5 minutes , 1h32m15s = 1 hour, 32 mins, 15 seconds)
              see: https://pkg.go.dev/time#ParseDuration

          http2.enabled:
            type: boolean
            default: false

          use_stdlib_json:
            type: boolean
            default: false

      max_file_descriptors:
        type: integer
        default: 5000
        description: |+
          Maximum number of open file descriptors.

  Logging_model:
    type: object
    title: Logging Model
    description: |+
      Holding object for all logging-related settings.

      Note that in addition to setting these logging values in the bootstrap configuration file, you can also use the ADMIN Rest API to set or change the values without requiring a full reload.
      See: [Rest Admin API](rest-api-admin.html)

      A full logging initialization is required.

      See the [Logging](logging.html) page for a fuller explanation on logging settings.

    properties:
      log_file_path:
        type: string
        description: |+
          Absolute or relative path on the filesystem to the log file.
          A relative path is from the directory that contains the Sync Gateway executable file.

          Changes require full logging re-initialization
      redaction_level:
        type: string
        default: none
        description: |+
          Optionally, log files can be redacted.
          This means that user-data, considered to be private, is removed.
          Such data includes:

            - Key/value pairs in JSON documents

            - Usernames

            - Query-fields that reference key/value pairs and/or usernames

            - Names and email addresses retrieved during product registration

            - Extended attributes

          This redaction of user-data is referred to as partial redaction.

          To enable it, set this property to `"redaction_level" : "partial"` in the configuration file:

      console:
        type: object
        description: Settings for the console output logging.
        properties:
          enabled:
            type: boolean
            description: Indicates whether console logging is enabled
          rotation:
            type: object
            description: |+
              The log file may be rotated by defining a "rotation" sub document.
              See details in [log rotation](logging.html#lbl-logrotate).
            properties:
              max_size:
                type: integer
                description: The maximum size in MB of the log file before it gets rotated.
                default: 100
              max_age:
                type: integer
                description: |+
                  The maximum number of days to retain old log files.
                  This can't be set below the minimum allowed value for the given level.
              localtime:
                type: boolean
                description: |+
                  If true, it uses the computer's local time to format the backup timestamp.
                  False uses UTC.
                default: false
              rotated_logs_size_limit:
                type: integer
                default: 1024
                description: |+
                  Controls how much disk space the rotated (and compressed) log files for this level can take up.

                  The value is expressed in megabytes.
                  The minimum value is `10` and there is no maximum value.
          collation_buffer_size:
            type: integer
            description: |+
              Size of the collation buffer

          log_level:
            type: string
            default: 'info'
            description: |+
              The level of logging.

              Log levels are cumulative (that is, log entries at WARN will also be included in the INFO and DEBUG logs).

              See:
              [Log Levels](logging.html#lbl-log-keys) page

          log_keys:
            description: |+
              List of log keys to enable for diagnostic logging.

              Available log key values are described in the
              [Log Keys](logging.html#lbl-log-keys) page

            type: array
            items:
              type: string
            default: '["HTTP"]'
          color_enabled:
            type: boolean
            default: false
            description: Use ANSI color codes in the console output (Linux/MacOS only).
          file_output:
            type: string
            description: |+
              Changes require full logging re-initialization
      error:
        description: |+
          Activate the error logging level - see [Logging](logging.html) page for more on log levels.
        type: object
        properties:
          enabled:
            description: |+
              Enable this *error* log level.

              - The *error*, *warn* and *info* log levels are enabled by default.

              - The *debug* log level is disabled by default.

              **Note:** You are advised to keep this log level enabled to troubleshoot issues.

              Enabling this log level is a requirement to receive
              [Enterprise Support](https://www.couchbase.com/support-policy).
            type: boolean
          rotation:
            type: object
            description: |+
              The log file may be rotated by defining a "rotation" sub document.

              See details in [log rotation](logging.html#lbl-logrotate).
            properties:
              max_size:
                type: integer
                description: The maximum size in MB of the log file before it gets rotated.
                default: 100
              max_age:
                type: integer
                description: The maximum number of days to retain old log files. This can't be set below the minimum allowed value for the given level.
              localtime:
                type: boolean
                description: If true, it uses the computer's local time to format the backup timestamp. False uses UTC.
                default: false
              rotated_logs_size_limit:
                type: integer
                default: 1024
                description: |+
                  Controls how much disk space the rotated (and compressed) log files for this level can take up.

                  The value is expressed in megabytes.
                  The minimum value is `10` and there is no maximum value.
          collation_buffer_size:
            type: integer
            description: |+
              Size of the collation buffer

      warn:
        description: |+
          The warning logging-level is triggered when Sync Gateway detects something is wrong but it can still service requests

          - Minimum max_age is 90 days

          - Log File Name is ```sg_warn.log```

        type: object
        properties:
          enabled:
            description: |+
              Whether to enable this log level.
              The *error*, *warn* and *info* log levels are enabled by default.
              The *debug* log level is disabled by default.

              Note, however, that you are advised to keep this log level enabled to troubleshoot issues. Enabling this log level is a requirement to receive [Enterprise Support](https://www.couchbase.com/support-policy).
            type: boolean
          rotation:
            type: object
            description: |+
              The log file may be rotated by defining a "rotation" sub document. See details in [log rotation](logging.html#lbl-logrotate).
            properties:
              max_size:
                type: integer
                description: The maximum size in MB of the log file before it gets rotated.
                default: 100
              max_age:
                type: integer
                description: The maximum number of days to retain old log files. This can't be set below the minimum allowed value for the given level.
              localtime:
                type: boolean
                description: If true, it uses the computer's local time to format the backup timestamp. False uses UTC.
                default: false
              rotated_logs_size_limit:
                type: integer
                default: 1024
                description: |+
                  Controls how much disk space the rotated (and compressed) log files for this level can take up.

                  The value is expressed in megabytes.
                  The minimum value is `10` and there is no maximum value.
          collation_buffer_size:
            type: integer
            description: |+
              Size of the collation buffer

      info:
        type: object
        description: |+
          The information logging-level provides important diagnostics for support and customers
        properties:
          enabled:
            type: boolean
            default: true
            description: |+
              Whether to enable this log level.

          rotation:
            type: object
            description: |+
              The log file may be rotated by defining a "rotation" sub document
            properties:
              max_size:
                type: integer
                description: The maximum size in MB of the log file before it gets rotated.
                default: 100
              max_age:
                type: integer
                description: The maximum number of days to retain old log files. This can't be set below the minimum allowed value for the given level.
              localtime:
                type: boolean
                description: If true, it uses the computer's local time to format the backup timestamp. False uses UTC.
                default: false
              rotated_logs_size_limit:
                type: integer
                default: 1024
                description: |+
                  Controls how much disk space the rotated (and compressed) log files for this level can take up.

                  The value is expressed in megabytes.
                  The minimum value is `10` and there is no maximum value.
          collation_buffer_size:
            type: integer
            description: |+
              Size of the collation buffer

      debug:
        type: object
        description: |+
          The debug logging-level provides lower level development analysis

          - Minimum max_age is 1 day
          _ Log File Name is ```sg_debug.log```
        properties:
          enabled:
            type: boolean
            default: false
            description: |+
              Sets this logging-level on or off.

              Note, you are advised to keep this log level enabled when troubleshooting issues.
              Enabling this log level is a requirement to receive [Enterprise Support](https://www.couchbase.com/support-policy).
          rotation:
            type: object
            description: |+
              The log file may be rotated by defining a "rotation" sub document. See details in [log rotation](logging.html#lbl-logrotate).
            properties:
              max_size:
                type: integer
                description: The maximum size in MB of the log file before it gets rotated.
                default: 100
              max_age:
                type: integer
                description: The maximum number of days to retain old log files. This can't be set below the minimum allowed value for the given level.
              localtime:
                type: boolean
                description: If true, it uses the computer's local time to format the backup timestamp. False uses UTC.
                default: false
              rotated_logs_size_limit:
                type: integer
                default: 1024
                description: |+
                  Controls how much disk space the rotated (and compressed) log files for this level can take up.

                  The value is expressed in megabytes.
                  The minimum value is `10` and there is no maximum value.
          collation_buffer_size:
            type: integer
            description: |+
              Size of the collation buffer

      trace:
        type: object
        description: |+
          The trace logging-level.
        properties:
          enabled:
            type: boolean
            default:
            description: |+
              Whether to enable this log level.

          rotation:
            type: object
            description: |+
              The log file may be rotated by defining a "rotation" sub document. See details in [log rotation](logging.html#lbl-logrotate).
            properties:
              max_size:
                type: integer
                description: The maximum size in MB of the log file before it gets rotated.
                default: 100
              max_age:
                type: integer
                description: The maximum number of days to retain old log files. This can't be set below the minimum allowed value for the given level.
              localtime:
                type: boolean
                description: If true, it uses the computer's local time to format the backup timestamp. False uses UTC.
                default: false
              rotated_logs_size_limit:
                type: integer
                default: 1024
                description: |+
                  Controls how much disk space the rotated (and compressed) log files for this level can take up.

                  The value is expressed in megabytes.
                  The minimum value is `10` and there is no maximum value.
          collation_buffer_size:
            type: integer
            description: |+
              Size of the collation buffer

      stats:
        type: object
        description: |+
          The stats logging level
        properties:
          enabled:
            type: boolean
            default:
            description: |+
              Whether to enable this log level.
          rotation:
            type: object
            description: |+
              The log file may be rotated by defining a "rotation" sub document. See details in [log rotation](logging.html#lbl-logrotate).
            properties:
              max_size:
                type: integer
                description: The maximum size in MB of the log file before it gets rotated.
                default: 100
              max_age:
                type: integer
                description: The maximum number of days to retain old log files. This can't be set below the minimum allowed value for the given level.
              localtime:
                type: boolean
                description: If true, it uses the computer's local time to format the backup timestamp. False uses UTC.
                default: false
              rotated_logs_size_limit:
                type: integer
                default: 1024
                description: |+
                  Controls how much disk space the rotated (and compressed) log files for this level can take up.

                  The value is expressed in megabytes.
                  The minimum value is `10` and there is no maximum value.
          collation_buffer_size:
            type: integer
            description: |+
              Size of the collation buffer


  Database_model:
    type: object
    title: "Database"
    description: |+
      This `database` object defines the JSON configuration of a sync gateway database.

      Provision the configuration using the request message body of a ```put /{db}/``` and-or ```put /{db}/_config```
      that comprises all the properties required to upsert a replication.

    properties:

      bucket:
        type: string
        default: "the database name"
        title: The Couchbase Server bucket name associated with this Sync Gateway database
        description: |+
          Defines the Couchbase Server bucket to be used for this Sync Gateway database
          bucket

          If not specified, then the database name is used as the bucket name.


      name:
        type: string
        description: |+
          Use `name` to define the Sync Gateway database name.

          Change initiates database restart

      sync:
        $ref: '#/definitions/Sync_model'

      guest:
        type: object
        description: |+
          Defines whether a GUEST user is available and able to interacted, unauthenticated, with the Public REST API
        properties:
          disabled:
            type: boolean
            default: true
            description: |+
              Set `disabled` = `false` to allow GUEST

              For example:
              ```curl -X PUT username:password@localhost:4985/db/_config -H "Content-Type: application/json" --data-binary '{"guest": {"disabled":false}}```

      revs_limit:
        type: integer
        description: |+
          This property defines the maximum depth to which a document's revision tree can grow.

          It value governs the point at which to prune a document's revision tree.

          For more information see: [Revisions](revisions.html) page.
      import_docs:
        type: boolean
        description: |+
          Use the `import_docs` property to define whether the Sync Gateway node should automatically import Couchbase Server documents;

          This property works in conjunction with the `enable_shared_bucket_access` property, which enables Xattrs.

          Since Sync Gateway 2.7, all Sync Gateway nodes can be configured as import nodes.
          This results in performance benefits as the import process is shared across all Sync Gateway nodes.

          Prior to version 2.7, `import_docs` can only be set to `true` on a single node.

          Changes initiate a database restart

        default: false

      import_partitions:
        type: integer
        description: |+
          Use the `import_partitions` property to define how many import partitions should be used for import sharding.

          Partitions are distributed among all Sync Gateway nodes participating in import processing (import_docs:true), and each process a subset of the server's vbuckets.

          Each partition is processed by a separate goroutine, so `import_partitions` can be used to tune concurrency based on the number of Sync Gateway nodes, and the number of cores per node.

        default: 16

      import_filter:
        $ref: '#/definitions/Import_filter_model'

      import_backup_old_rev:
        type: string
        description: |+
          Use the `import_backup_old_rev` property to define whether import should attempt to create a temporary backup of the previous revision body, when available

      event_handlers:
        type: object
        title: "Event Handler"
        description: |+
          Webhooks in Sync Gateway are designed to minimize performance impacts on Sync Gateway's regular processing.

          Sync Gateway manages the number of processes that are spawned for webhook event handling, so that slow response times from the HTTP POST operations don't consume available CPU resources on Sync Gateway nodes.

          When a `webhook` event handler is defined, after Sync Gateway has updated a document, Sync Gateway adds a `document_changed` event to an asynchronous event-processing queue (the event queue).

          New processes are then spawned to apply the `filter` function to the documents and to perform the HTTP POST operations.

          When an event is not added to the event queue, but is instead discarded, a warning message is written to the the Sync Gateway log.

          You can configure Sync Gateway to log information about event handling, by including either the log key ```Event``` or ```Events+``` in the `Log` property in your Sync Gateway configuration file. `Events+` is more verbose.

          See also:
          [Webhook](webhooks.html)..

        properties:
          document_changed:
            title: "Document Changed"
            description: The configuration for the action to perform when a document change is detected.
            properties:
              filter:
                type: string
                description: |+
                  Use ```document_changed.filter``` to define a JavaScript function that determines which documents to post.

                  The filter function accepts the document body as input and returns a boolean value.

                  - If the filter function returns true, then Sync Gateway posts the document.

                  - If the filter function returns false, then Sync Gateway does not post the document.

                  - If no filter function is defined, then Sync Gateway posts all changed documents.

                  Filtering only determines which documents to post.
                  It does not extract specific content from documents and post only that.

              handler:
                type: string
                description: |+
                  Specify the type of event handler.

                  This must be `webhook` currently).
              options:
                type: string
                description: |+
                  Options can be specified per-handler, and are specific to each handler type.
              timeout:
                type: integer
                description: |+
                  Defines the period in seconds to wait for a response to the POST operation.

                  Using a timeout ensures that slow-running POST operations don't cause the webhook event queue to back up.

                  Slow-running POST operations are discarded (if they time out), so that new events can be processed.
                  When the timeout is reached, Sync Gateway stops listening for a response.

                  A value of 0 (zero) means no timeout.

                  You should not need to adjust it to tune performance as he default value should work well in the majority of cases.
                default: 60
              url:
                description: |+
                  Defines the URL to post documents to (for a webhook event handler).
                type: string
                # required: true

          db_state_changed:
            description: |+
                Use the `db_state_changed` property group to define the actions to perform when a `db_state` change is detected.
            title: db_state_changed model
            type: object
            properties:
              filter:
                type: string
                description: |+
                  Use `db_state_changed.filter``` to define a JavaScript function that determines which state changes to post.
              handler:
                type: string
                description: |+
                  Specify the type of event handler.

                  This must be `webhook` currently).
              options:
                type: string
                description: |+
                  Options can be specified per-handler, and are specific to each handler type.
              timeout:
                type: integer
                description: |+
                  Defines the period in seconds to wait for a response to the operation.
                  Default: 60
              url:
                type: string
                description: |+
                  Defines the URL to post to (for a webhook event handler).

          max_processes:
            type: integer
            description: |+
              Maximum number of events that can be processed concurrently, that is, no more than `max_processes` concurrent processes will be spawned for event handling.

              The default value should work well in the majority of cases.
              You should not need to adjust it to tune performance.
              However, if you wish to ensure that most webhook posts are sent, you can set it to sufficiently high value.
            default: 500

          wait_for_process:
            type: string
            description: |+
              Maximum wait time in milliseconds before canceling event processing for an event that is detected when the event queue is full.

              If you set the value to 0 (zero), then incoming events are discarded immediately if the event queue is full.

              If you wish to avoid any blocking of standard Sync Gateway processing this may be a desirable value to use.

              The default value should work well in the majority of cases. You should not need to adjust it to tune performance.
            default: 100
      allow_empty_password:
        type: boolean
        description:
          Use ```allow_empty_password``` to define whether to Sync Gateway users can be created with empty passwords.
        default: false

      cache:
        type: object
        title: "Cache"
        description: |+
          The `cache` group of properties define the  configuration for this database's channel and revision caches

        properties:
          rev_cache:
            type: object
            title: "Revision Cache"
            description: |+
              Use the `rev_cache` properties to configure the revision cache
            properties:
              size:
                type: integer
                description: |+
                  Size of the revision cache, specified as the total number of document revisions to cache in memory for all recently accessed documents.

                  When the revision cache is full, Sync Gateway removes less recent document revisions to make room for new document revisions.
                  Adjust this property to tune memory consumption by Sync Gateway, for example on servers with less memory and in cases when Sync Gateway creates many new documents and/or updates many documents relative to the number of read operations.

                  *Disabling the revision cache*

                  Disabling the revision cache is an [Enterprise Edition](https://www.couchbase.com/products/editions) feature.

                  To disable the revision entirely, set this property to 0.
                  Setting this property to 0 on the Community Edition is ignored.

                  Disabling the revision cache would be useful when there are very large documents or if you expect a very low cache hit rate.
                  Otherwise it could negatively impact the latency of replications.
                  It is generally not recommended to disable the revision cache, unless advised by Couchbase
                  [Enterprise Support](https://www.couchbase.com/support-policy).
                default: 5000
              shard_count:
                type: integer
                description: |+
                  Tuning this property is an [Enterprise Edition](https://www.couchbase.com/products/editions) feature.
                  The Community Edition is configured with the default value, and will ignore any value in the configuration file.

                  Number of shards the rev cache should be split into. More shards allows for lower cache contention when accessing distinct revisions, at the cost of some memory overhead per-shard.
                  This generally should not greatly exceed the number of CPU threads available to Sync Gateway.

                  It is generally not recommended to set this property, unless advised by Couchbase [Enterprise Support](https://www.couchbase.com/support-policy).
                default: 8

          channel_cache:
            type: object
            title: "Channel Cache"
            description: |+
              Use the `channel_cache` group's properties to configure the database's channel cache

              Changes initiate a database restart
            properties:
              compact_high_watermark_pct:
                type: integer
                description: |+
                  Use ```compact_high_watermark_pct``` to define the trigger value for starting channel cache eviction.
                  Specify the value as a percentage (of ```max_number```)

                  When the cache size, determined by `max_number`, reaches the high watermark, the eviction process iterates through the cache, removing inactive channels.
                default: 80
              compact_low_watermark_pct:
                type: integer
                description: |+
                  Use ```compact_low_watermark_pct``` to define the trigger value for stopping channel cache eviction.
                  Specify the value as a percentage (of ```max_number```)

                  When the cache size, determined by `max_number` returns to a value lower than `compact_low_watermark_pct`, the cache eviction process is stopped.
                default: 60

              enable_star_channel:
                type: boolean
                description: |+
                  Use ```enable_star_channel``` to define whether Sync GAteway should use the all documents (*) channel - sometimes referred to as the 'star' channel.

                default: true

              expiry_seconds:
                type: integer
                description: |+
                  Use ```expiry_seconds``` to define how long (in seconds) Sync Gateway should keep cached entries beyond the minimum retained.
                default: 60

              max_length:
                type: integer
                description: |+
                  Maximum number of entries maintained in cache per channel.
                default: 500

              max_num_pending:
                type: integer
                description: |+
                  Use ```max_num_pending``` to define the maximum number of pending sequences before skipping the sequence.
                default: 10000

              max_number:
                type: integer
                description: |+
                  Use ```max_number``` to define the maximum number of channel caches allowed at any one point.
                  This property is used alongside the associated eviction watermarks ```compact_low_watermark_pct``` and ```compact_high_watermark_pct``` to control the cache size.

                  The default value for this property is 50000.
                  Assuming the default channel `min_length` and `max_length` values, this would result in a memory usage under 1GB.

                  Tuning this property is an [Enterprise Edition](https://www.couchbase.com/products/editions) feature - in the Community Edition any change to the default value is ignored.

                  *Enterprise Edition Only*:
                    The `max_number` value can be tuned to optimize for cache hits (requests that are handled using the cache), as opposed to cache misses (requests that require a round-trip to Couchbase Server to fetch data).
                    The cache hit/miss ratio can be obtained with the following:

                  ```cache hit/miss ratio``` = ```cache.chan_cache_hits``` / ```cache.chan_cache_misses```

                  Increasing the `max_number` value can increase the cache hit/miss ratio, resulting in better cache utilization.

                  If the cache size grows to reach the high watermark (`compact_high_watermark_pct`), channels with no connected replications will be evicted before channels which are associated with an active pull replication (i.e a blip-based pull replication in Couchbase Lite 2.x, or an active `/{db}/_changes` request in Couchbase Lite 1.x).

                  The minimum allowed value is 100.

                  It isn't possible to remove the limit altogether, users who wish to remove the limit would need to set `max_number` to an arbitrarily high value.
                default: 50000

              max_wait_pending:
                type: integer
                description: |+
                  Maximum wait time in milliseconds for a pending sequence before skipping sequences.
                default: 5000

              max_wait_skipped:
                type: integer
                description: |+
                  Maximum wait time in milliseconds for a skipped sequence before abandoning the sequence.
                default: 3600000
              min_length:
                type: integer
                description: |+
                  Minimum number of entries maintained in cache per channel.
                default: 50
              query_limit:
                type: integer
                default: 5000
                description: Limit used for channel queries

      offline:
        type: boolean
        description: |+
          Use `offline` to determine whether Sync Gateway should start the database in offline mode.

          The default of false means the database will be online.
        default: false

      unsupported:
        title: "Unsupported Properties Model"
        type: object
        description: |+
          This group comprises an unrelated collection of unsupported properties that may, potentially, be useful in controlled testing scenarios.

          NOTE: Due to the unsupported nature of these options, there is no guarantee on their continued availability.
        properties:
          api_endpoints:
            type: object
            properties:
              enable_couchbase_bucket_flush:
                type: boolean
                description: |+
                  Determines whether Couchbase buckets can be flushed using the Admin REST API.

                  Use *only* for testing purposes if it is necessary to flush data in between tests to start with a clean DB.

          oidc_tls_skip_verify:
            type: boolean
            default: false
            description: |+
              Unsupported option for use in development and testing environment ONLY

              `oidc_tls_skip_verify` can be used to enable the use of self-signed certs for OpenID Connection testing.

          oidc_test_provider:
            type: object
            description:  Config settings for OIDC test provider
            properties:
              enabled:
                type: boolean
                description: |+
                  Unsupported option for use in development and testing environment ONLY

                  Determines whether the oidc_test_provider endpoints should be exposed on the public API.
          remote_config_tls_skip_verify:
            type: boolean
            default: false
            description: |+
              Unsupported option for use in development and testing environment ONLY

              Use only to enable self signed certificates for testing external JavaScript load.
          sgr_tls_skip_verify:
            type: boolean
            default: false
            description: |+
              Unsupported option for use in development and testing environment ONLY

              `sgr_tls_skip_verify` can be used to skip validation of TLS certs used for Inter-Sync Gateway Replication.

          user_views:
            type: object
            description: Configuration settings for user views
            default: 'none'
            properties:
              user_views_enabled:
                type: boolean
                description: |+
                  Unsupported option for use in development and testing environment ONLY

                  Use to determine whether pass-through view query is supported through public API

          warning_thresholds:
            type: object
            title: "Warning Threshold"
            properties:
              access_and_role_grants_per_doc:
                type: boolean
                description: |+
                  Number of access and role grants per document to be used as a threshold for grant count warnings
              channels_per_doc:
                type: boolean
                description: |+
                  Number of channels per document to be used as a threshold for channel count warnings
              channels_per_user:
                type: boolean
                description: |+
                  Number of channels per user to be used as a threshold for channel count warnings
              channel_name_size:
                type: boolean
                description: |+
                  Number of channel name characters to be used as a threshold for channel name warnings


              xattr_size_bytes:
                type: boolean
                description: |+
                  Number of bytes to be used as a threshold for XATTR size limit warnings
          disable_clean_skipped_query:
            type: boolean
            description: Clean skipped sequence processing bypasses final check

      oidc:
        type: object
        title: "OIDC Group"
        description: |+
          Use the `oidc` object properties to defined any OpenID Connect providers and associated credentials.
        properties:
          default_provider:
            type: string
            description: |+
              Use this `default_provider` property to identify the provider to use for OIDC requests that do not specify a provider.

              If only one provider is specified in the providers map, then that is used as the default provider.
              If multiple providers are defined and default_provider is not specified, requests to ```/db/_oidc``` must specify the provider parameter.

          providers:
            title: "OIDC Providers"
            description: Include an entry for each OIDC provider
            type: object
            properties:
              this_provider:
                title: "OIDC Provider"
                type: object
                properties:

                  issuer:
                    type: string
                    description: The OpenID Connect Provider issuer.

                  register:
                    type: string
                    description: |+
                      Whether Sync Gateway should automatically create users for successfully authenticated users that don't have an already existing user in Sync Gateway.

                      Optional.

                  client_id:
                    type: string
                    description: The client ID defined in the provider for Sync Gateway.

                  validation_key:
                    type: string
                    description: Client secret associated with the client. Required for auth code flow.

                  callback_url:
                    type: string
                    description: |+
                      The callback URL to be invoked after the end-user obtains a client token.
                      When not provided, Sync Gateway will generate it based on the incoming request.

                      *Optional*

                  disable_session:
                    type: string
                    description: |+
                      By default, Sync Gateway will create a new session for the user upon successful OIDC authentication, and set that session in the usual way on the _oidc_callback and _oidc_refresh responses.

                      If disable_session is set to true, the session is not created (clients must use the ID token for subsequent authentications).

                      *Optional*

                  scope:
                    type: string
                    description: |+
                      By default, Sync Gateway uses the scope "openid email" when calling the OP's authorize endpoint.

                      If the scope property is defined in the config (as an array of string values), it will override this scope.

                      *Optional. *

                  include_access:
                    type: string
                    description: |+
                      Optional.
                      When true, the oidccallback response will include the access_token, expires_at and token_type properties returned by the OP.

                  user_prefix:
                    type: string
                    description: |+
                      Optional.
                      Specifies the prefix for Sync Gateway usernames for the provider.
                      When not specified, defaults to issuer.

                  discovery_url:
                    type: string
                    description: |+
                      Optional.
                      Discovery URL used to obtain the OpenID Connect provider configuration.
                      If not specified, the default discovery endpoint of [issuer]/.well-known/openid-configuration will be used.

                  disable_cfg_validation:
                    default: false
                    type: boolean
                    description: |+
                      Couchbase Sync Gateway, by default, applies strict validation of the OpenID Connect configuration based on the OIDC specification.

                      Set ```"disable_cfg_validation": true``` when you do not want strict validation of the OIDC configuration.

                  disable_callback_state:
                    default: false
                    type: boolean
                    description: |+
                      DisableCallbackState determines whether or not to maintain state between the ```/_oidc``` and
                      ```/_oidc_callback``` endpoints.

                      Disabling this action is NOT recommended as it will increase vulnerability to Cross-Site Request Forgery (CSRF, XSRF).

                      Set ```"disable_callback_state": true``` to switch-off callback state.

                  username_claim:
                    type: string
                    default: 'optional'
                    description: |+

                        You can use `username_claim` to specify a claim other than subject to use as the Sync Gateway username.

                        The specified claim must be a string, as numeric claims may be un-marshalled inconsistently between Sync Gateway and the underlying OIDC library.

                        When authenticating incoming OIDC tokens, Sync Gateway currently treats the username as [user_prefix]_[subject].
                        By default user_prefix is the issuer, but can be customized in the Sync Gateway provider config.
                        Subject is always the sub claim in the token.

                        Behavior:

                        - If username_claim is set but user_prefix is not set, use that claim as the Sync Gateway username.

                        - If username_claim is set and user_prefix is also set, use [user_prefix]_[username_claim] as the Sync Gateway username.

                        - If username_claim is not set and user_prefix is set, use [user_prefix]_[subject] as the Sync Gateway username (existing behavior).

                        - If neither username_claim nor user_prefix are set, use [issuer]_[subject] as the Sync Gateway username (existing behavior).

                  allow_unsigned_provider_tokens:
                    type: boolean
                    default: false
                    description: |+
                      Unsigned provider tokens are not accepted.

                      Set ```"allow_unsigned_provider_tokens": true``` to opt-in to accepting unsigned tokens from providers.

      old_rev_expiry_seconds:
        type: integer
        description: |+
          Use the `old_rev_expiry_seconds` property to define the number of seconds before old revisions are removed from Couchbase Server buckets.

      view_query_timeout_secs:
        type: integer
        description: |+
          Use the `view_query_timeout_secs` property to define the view query timeout in seconds.

          This is the time Sync Gateway should wait for a view query response from Couchbase Server before it times out.

          The timeout applies to both view and N1QL queries issued by Sync Gateway.
        default: 75

      local_doc_expiry_secs:
        type: integer
        description: |+
          Use the `local_doc_expiry_secs` property to define an expiry value for local documents managed on Sync Gateway.

          Local documents are used by the Couchbase Lite replicator to track up to which sequence number a given client has synchronized and where it should resume the next time it connects to Sync Gateway.

          Clients failing to replicate within the expiry window are forced to restart their replication from the beginning (sequence zero).

          This property is intended to minimize accumulation of obsolete replication checkpoint documents in the Couchbase Server bucket.

          The default is `7776000` seconds (90 days).
        default: 7776000

      enable_shared_bucket_access:
        type: boolean
        default: true
        description: |+
          Use the `enable_shared_bucket_access` property to define whether to use extended attributes to store sync metadata.
          This is required to enable mobile-to-server data sync (_mobile convergence_).

          You can learn more about this functionality in [Syncing with Couchbase Server](sync-with-couchbase-server.html)

          This property works in conjunction with the  ```import_docs``` property, which determines whether a node participates in import processing.
          Leave `enable_shared_bucket_access` `true` on all nodes participating in such a configuration.

          On start-up, Sync Gateway will generate the mobile-specific metadata for all the pre-existing documents in the Couchbase Server bucket. From then on, documents can be inserted on the Server directly (with N1QL or SDKs) or through the Sync Gateway REST API.

          Change initiates a database restart


      session_cookie_secure:
        type: boolean
        default: true
        description: |+
          Override secure cookie flag (that is, disable secure cookies).

          If SSLCert is set, then secure cookies are also used by default.
          However, this flag can be set `false` to override this behavior and allow insecure cookies to be used alongside SSL.

          If SSLCert is not set then this flag defaults to false.

      session_cookie_name:
        type: string
        description: |+
          Starting in Sync Gateway 2.0, it is possible to customize the session cookie name that is used for this database.

          This property is mostly used by web applications interacting with multiple Sync Gateway databases.

          Browsers typically have two methods of determining which cookie to use for a given request: the `URL` path, or the cookie name.

          Use this property, to set different cookie names for each database specified in the configuration file. Let's consider the following configuration file:

          ```json
          {
              "databases": {
                "db1": {
                  "session_cookie_name": "CustomName1",
                  "bucket": "bucket-1"
                  },
                  "db2": {
                    "session_cookie_name": "CustomName2",
                    "bucket": "bucket-2"
                  }
                }
              }
          }
          ```

          With this configuration, the `Set-Cookie` response header of the POST `:4984/{db}/_session` endpoint (Public REST API) would then have the form "CustomName1=3cad4b95524179bf144fe0d92b8f09877bb86bf5;path=/db1/".

          When using POST `:4985/{db}/_session` (Admin REST API) to create a session, the cookie value is returned in the response body instead of the `Set-Cookie` header. In this case, it could also be set by the client, for web applications it would be the following in JavaScript:

          ```javascript
          cookie1String = "CustomName1=3cad4b95524179bf144fe0d92b8f09877bb86bf5;path=/db1/";
          document.cookie = cookie1String;
          ```
        default: 'SyncGatewaySession'

      session_cookie_http_only:
        type: boolean
        default: false
        description:  This flag disallows cookies from being used by Javascript; by default javascript CAN use them

      allow_conflicts:
        type: boolean
        description: |+
          Use ```allow_conflict``` to define whether Sync Gateway will handle conflicts.

          The default of ```true``` indicates that conflicts are handled.

          Set the value to ```false``` to cause Sync Gateway to reject any attempt to write conflicting revisions (returning a `409` HTTP status code).
          It will be up to the client to resolve the conflict.

          Restarting Sync Gateway with this property enabled will not automatically result in disk space savings (compaction on a document won't occur until a document is updated).

          *Constraints:*
          - Push replications to pre-2.8 targets do not support the `"allow_conflicts": false` setting; the target must use `"allow_conflicts": true`.

          Change initiates a database restart.
        default: true

      num_index_replicas:
        type: integer
        description: |+
          use `num_index_replicas` property to define the number of index replicas used when creating the core Sync Gateway indexes.

          Only applicable if `databases.$db.use_views` is set to `false` (default value).

          Change initiates a database restart.
        default: 1

      use_views:
        type: boolean
        description: |+
          If set to `true`, Sync Gateway will use views instead of GSI for system functions like authentication and replication.
        default: false

      send_www_authenticate_header:
        type: boolean
        description: Whether to send WWW-Authenticate header in 401 responses.
        default: true

      bucket_op_timeout_ms:
        type: integer
        description: |+
          Use ```bucket_op_timeout_ms``` to define how long Sync Gateway will wait for a bucket operation to complete before timing out and trying again.

          You may increase this value where there is a heavy load on Couchbase Server and operations are likely to take more than 2.5 seconds to complete.

          The default value is 2500 milliseconds.

          Changes initiate a database restart.
        default: 2500

      delta_sync:
        type: object
        title: "Delta Sync"
        description: |+
          *NOTE:* Delta Sync is an Enterprise Edition feature on Sync Gateway and Couchbase Lite.

          Use the `delta_sync ` object to specify the delta sync configuration properties.

          In this context, delta-sync, is the ability to replicate only those parts of a Couchbase mobile document that have changed.
          This results in significant savings in bandwidth consumption as well as throughput improvements; both useful benefits when network bandwidth is typically constrained.

          Delta Sync does not apply to attachment contents.

          Delta Sync is disabled by default on the Sync Gateway. You can enable it through the `enabled` property.

          If delta sync is enabled on Sync Gateway, then Couchbase Lite clients will switch to using delta sync automatically.
          Similarly, if delta sync is disabled on Sync Gateway, clients will switch to normal mode.

          Changes initiate a database reload
        properties:
          enabled:
            type: boolean
            description: |+
              Use the ```delta_sync.enabled``` property to turn delta sync mode on or off for the given database.

              The following configuration example enables delta sync.

              ```json
              {
                "databases": {
                  "db": {
                    "delta_sync": {
                      "enabled": true,
                      "rev_max_age_seconds": 86400
                    }
                  }
                }
              }
              ```

              Footnotes

              - Use of Delta Sync incurs additional bucket storage requirements which can be tuned with the [`rev_max_age_seconds`](#databases-this_db-delta_sync-rev_max_age_seconds) property.

              - Delta Sync is automatically enabled for peer-to-peer sync between Couchbase Lite clients.

              - Delta sync is disabled for Couchbase Lite database replicas.

              - Push replications do not use Delta Sync when pushing to a pre-2.8 target.

            default: false
          rev_max_age_seconds:
            type: integer
            description: |+
              Use ```delta_sync.rev_max_age_seconds``` to adjust the time box within which deltas can be generated.

              On a write operation, the revision body is backed up in the bucket and retained for `rev_max_age_seconds` to calculate future revision deltas.
              As a result, new deltas can only be generated for read requests that come in within the `rev_max_age_seconds` time window.
              The storage of backed up revision bodies for delta sync incurs additional bucket storage requirements.

              The additional storage can be calculated with the following formula: `(doc_size * updates_per_day * 86400) / rev_max_age_seconds`.

              For example, with `rev_max_age_seconds`'s default value, an average document size of 4 KB and 100 writes/day, enabling delta sync would take up an additional 400 KB of storage on Couchbase Server (`(4 * 100 * 86400)/86400`).

              Setting this value to 0 will generate deltas opportunistically on pull replications, with no additional storage requirements.
            default: 86400

      compact_interval_days:
        type: number
        description: |+
          Use `` property to define the interval between scheduled compaction runs (in days).

          Set a zero (0) value to suppress running compactions.

          Change initiates a database restart.

      isgr_enabled:
        type: boolean
        default: true
        description: |+
          Use the `isgr_enabled` property to define whether this Sync Gateway node can be assigned inter-Sync Gateway replications for this database.

          If set to false, the Sync Gateway node will not participate in inter-Sync Gateway replications.

      isgr_websocket_heartbeat_secs:
        type: integer
        default: 300
        description: |+
          If set, this duration (in seconds) is used as a custom heartbeat interval for websocket ping frames in inter-Sync Gateway replications.

      serve_insecure_attachment_types:
        type: boolean
        default: false
        description: |+
          The sending of a content-disposition header for attachments with headers such as "text/html"
          forces a download, rather than browser rendering.

          Use this option to suppress sending the content-disposition, allowing the browser to render the attachment.

      query_pagination_limit:
        type: integer
        description: |+
          Use the `query_pagination_limit` property to define the Query limit to be used during pagination of large queries.

          Change initiates a database restart.

      slow_query_warning_threshold:
        type: integer
        default: 500
        description: |+
          The maximum wait time, in milliseconds,for N1QL or View queries made by Sync Gateway

          Log warnings if the run time of a N1QL or View query, made by Sync Gateway, exceeds this value.

      user_xattr_key:
        type: string
        default: none
        description: |+
          The ```user_xattr_key``` identifies the user xattr used to hold the channel access grants for documents in this database.

          If it is not specified or its value is spaces or null then this feature is disabled (default).

          If you change the value of this key, no existing grant assignments will be changed until a document mutation is triggered.
          This can be done in a number of ways:
          - a mutation to the document which we'll see via DCP
          - an on-demand import either through write or get
          - by using the resync function.

          *Dependencies:*
            The `user_xattr_key` feature requires that --

            - `enable_shared_bucket_access` be = `true`

            - xattrs be supported on the connected Couchbase Server

          Change initiates a database restart

      client_partition_window_secs:
        type: string
        default: 2592000
        description: |+
          Use the `client_partition_window_secs` property to define how long clients can remain offline for without losing replication metadata.

          Default 2 592 000 seconds (30 days)

  Import_filter_model:
    type: string
    description: |+
      The `import_filter` controls whether a document written to the Couchbase Server bucket should be made available to Couchbase Mobile clients (that is, whether it ought to be imported).

      You should provision the filter as a Javascript function in the request body of a call to the Admin Rest API endpoint ```put {db}/_config/import_filter```.

      Set the header's content type to ```content-Type: application/javascript```.

      The function takes the document body as parameter and is expected to return a boolean to indicate whether the document should be imported.

      If you do not provide a filter function then no filter will be applied and ALL documents will be imported.
    default: "No filter"
    example: |+
      function(doc) {
        if (doc.type != 'mobile') {
          return false
        }
        return true
      }

  Role_model:
    title: "Role Configuration Model"
    type: object
    description: |+
      Use the `role` property to define a Sync Gateway role
    required:
      - name
    properties:
      name:
        type: string
        description: |+
          Name of the role
      admin_channels:
        type: array
        description: |+
          Array of channel names the role allows access to
        items:
          type: string
      all_channels:
        type: array
        readOnly: true
        description: |+
          Lists all the channels the role has access to including any assigned by the `sync` function.

          This is a derived property and changes to it are ignored.
        items:
          type: string

  Role_and_User_model:
    type: object
    properties:
      Role:
        $ref: "#/definitions/Role_model"
      User:
         $ref: "#/definitions/User_model"

  Sync_model:
    type: string
    description: |+
      The `sync` property is a Javascript function that determines which users can access which documents.

      This JavaScript function is provisioned using the Admin Rest API Endpoint
      ```put /{db}/_config/sync```

      Add the function as plain javascript in the request body, with the ```content-Type: application/javascript``` header.

    default: |+
      `function(doc, oldDoc) {channel(doc.channels);}`
    example: |+
      function(doc, oldDoc) {
        channel(doc.channels);
      }

  User_model:
    type: object
    title: "User Configuration Model"
    description: |+
      Definition of a Sync Gateway user

      Change initiates database restart

    required:
      - name
    properties:
      name:
        type: string
        description: |+
          The user name (the same name used in the URL path).

          The valid characters for a user name are alphanumeric ASCII characters and the underscore character.

          The name property is required in a POST request.

          You don't need to include it in a PUT request because the user name is specified in the URL.
      password:
        type: string
        description: |+
          Password of the user.

          Mandatory, unless `allow_empty_password=true`.

      admin_channels:
        type: array
        description: |+
          The channels that the user is able to access.
        items:
          type: string
          description: |+
            Channel name

      admin_roles:
        type: array
        description: |+
          An array of the roles this user is associated with.
        items:
          type: string
          description: Role name

      all_channels:
        type: array
        description: |+
          Shows the channels the user can access, as granted by the sync function.

          This is a read-only property.
          Changes to it are ignored.
        readOnly: true
        items:
          type: string
          description: Channel name
      email:
        type: string
        description: |+
          Email address of the user.
      disabled:
        type: boolean
        description: |+
          This property is usually not included.

          If the value is `true`, access for the account is disabled and the user will not be able to login.
      roles:
        type: array
        readOnly: true
        description: |+
          Shows the roles this user is associated with by the Sync function.

          This is a read-only property.
          Changes to it are ignored.

        items:
          type: string
          description: Role name

  User-response:
    type: object
    properties:
      name:
        type: string
        description: |+
          The user name (the same name used in the URL path).

      admin_channels:
        type: array
        description: |+
          The channels that the user is able to access.
        items:
          type: string
          description: |+
            Channel name

      all_channels:
        type: array
        description: |+
          Shows the channels the user can access, as granted by the sync function.

        readOnly: true
        items:
          type: string
          description: Channel name

      email:
        type: string
        description: |+
          Email address of the user.
      disabled:
        type: boolean
        description: |+
          This property is usually not included.
          If the value is `true`, access for the account is disabled and the user will not be able to login.


  AllDatabases:
    type: array
    description: List of available databases in cluster
    items:
      type: string
      description: Database name


  ActiveTasks_model:
    type: object
    properties:
      source:
        type: string
        description: The URL of the source database (i.e `"http://example.com:4985/source"`).
      target:
        type: string
        description: The URL of the target database (i.e `"http://example.com:4985/target"`).
      continuous:
        type: boolean
        description: Whether the replication is continuously monitoring for changes on the source database to send them to the target.
      replication_id:
        type: string
        description: The replication Id.
      direction:
        type: string
        description: Inter-Sync Gateway Replication (v1) is uni-directional; valid values are **push** or **pull**.
      docs_read:
        type: integer
        description: The number of docs that have been read (fetched) from the source database.
      docs_written:
        type: integer
        description: The number of docs that have been written (pushed) to the target database.
      doc_write_failures:
        type: integer
        description: |+
          The number of docs that have failed to be written (pushed) to the target database.
          These docs will not be retried.
      end_last_seq:
        type: integer
        description: |+
          *Deprecated* The most recent `last_seq` value received from the source database during replication.
          Use the **last_seq_push** and **last_seq_pull** values instead.
      # start_last_seq:
      #   type: integer
      #   description: Not populated
      is_persistent:
        type: boolean
        description: flag to distinguish between the persistent and adhoc replications
      status:
        type: string
        description: |+
          Stopped / running

          These will be  **adhoc** replications (running) or persistent replications (stopped or running).
      last_seq_push:
        type: integer
        description:  |+
          The last seq number pushed from the source to target.

          The last_seq_push result can be used by apps to determine if a specific document has been synced to target or not. Do this by querying the **_raw** endpoint and comparing the sequence number of document with the last_seq value that was replicated.
      last_seq_pull:
        type: integer
        description:  |+
          The last seq number pulled from the source to target.

          The last_seq_pull result can be used by apps to determine if a specific document has been synced to target or not. Do this by querying the **_raw** endpoint and comparing the sequence number of document with the last_seq value that was replicated.

  DocMetadata:
    type: object
    properties:
      _sync:
        type: object
        properties:
          rev:
            type: string
            description: Revision number of the current revision
          sequence:
            type: integer
            description: Sequence number of this document
          recent_sequences:
            type: array
            items:
              type: integer
              description: Previous sequence numbers
          parents:
            type: array
            items:
              type: integer
              description: N/A
          history:
            type: object
            properties:
              revs:
                type: array
                items:
                  type: string
                  description: N/A
              parents:
                type: array
                items:
                  type: integer
                  description: N/A
              channels:
                type: array
                items:
                  type: string
                  description: N/A
              time_saved:
                type: string
                description: Timestamp of the last operation?

  Error:
    type: object
    properties:
      code:
        type: integer
        format: int32
      message:
        type: string
      fields:
        type: string

  SGCollectInfoStats:
    type: object
    properties:
      status:
        type: string
        description: The current status of sgcollect_info

  ExpVars:
    type: object
    properties:
      cmdline:
        type: object
        description: Built-in variables from the Go runtime, lists the command-line arguments
      memstats:
        type: object
        description: Dumps a large amount of information about the memory heap and garbage collector
      cb:
        type: object
        description: Variables reported by the Couchbase SDK (go_couchbase package)
      mc:
        type: object
        description: Variables reported by the low-level memcached API (gomemcached package)
      syncGateway_changeCache:
        type: object
        properties:
          maxPending:
            type: object
            description: Max number of sequences waiting on a missing earlier sequence number
          lag-tap-0000ms:
            type: object
            description: Histogram of delay from doc save till it shows up in Tap feed
          lag-queue-0000ms:
            type: object
            description: Histogram of delay from Tap feed till doc is posted to changes feed
          lag-total-0000ms:
            type: object
            description: Histogram of total delay from doc save till posted to changes feed
          outOfOrder:
            type: object
            description: Number of out-of-order sequences posted
          view_queries:
            type: object
            description: Number of queries to channels view
      syncGateway_db:
        type: object
        properties:
          channelChangesFeeds:
            type: object
            description: Number of calls to db.changesFeed, i.e. generating a changes feed for a single channel.
          channelLogAdds:
            type: object
            description: Number of entries added to channel logs
          channelLogAppends:
            type: object
            description: Number of times entries were written to channel logs using an APPEND operation
          channelLogCacheHits:
            type: object
            description: Number of requests for channel-logs that were fulfilled from the in-memory cache
          channelLogRewrites:
            type: object
            description: Number of times entries were written to channel logs using a SET operation (rewriting the entire log)
          channelLogRewriteCollisions:
            type: object
            description: Number of collisions while attempting to rewrite channel logs using SET
          document_gets:
            type: object
            description: Number of times a document was read from the database
          revisionCache_adds:
            type: object
            description: Number of revisions added to the revision cache
          revisionCache_hits:
            type: object
            description: Number of times a revision-cache lookup succeeded
          revisionCache_misses:
            type: object
            description: Number of times a revision-cache lookup failed
          revs_added:
            type: object
            description: Number of revisions added to the database (including deletions)
          sequence_gets:
            type: object
            description: Number of times the database's lastSequence was read
          sequence_reserves:
            type: object
            description: Number of times the database's lastSequence was incremented
      syncgateway:
        type: object
        description: Monitoring stats
        properties:
          global:
            type: object
            description: Global Sync Gateway stats
            properties:
              resource_utilization:
                type: object
                description: Resource utilization stats
                properties:
                  admin_net_bytes_recv:
                    type: integer
                  admin_net_bytes_sent:
                    type: integer
                  error_count:
                    type: integer
                  go_memstats_heapalloc:
                    type: integer
                  go_memstats_heapidle:
                    type: integer
                  go_memstats_heapinuse:
                    type: integer
                  go_memstats_heapreleased:
                    type: integer
                  go_memstats_pausetotalns:
                    type: integer
                  go_memstats_stackinuse:
                    type: integer
                  go_memstats_stacksys:
                    type: integer
                  go_memstats_sys:
                    type: integer
                  goroutines_high_watermark:
                    type: integer
                  num_goroutines:
                    type: integer
                  process_cpu_percent_utilization:
                    type: integer
                  process_memory_resident:
                    type: integer
                  pub_net_bytes_recv:
                    type: integer
                  pub_net_bytes_sent:
                    type: integer
                  system_memory_total:
                    type: integer
                  warn_count:
                    type: integer
          per_db:
            type: array
            description: |+
              This array contains stats for all databases declared in the config file - see the [Sync Gateway Statistics Schema](stats-monitoring.html) for more details on the metrics collected and reported by Sync Gateway.

              The statistics for each {$db_name} database are grouped into:

              - cache related statistics
              - cbl_replication_push
              - cbl_replication_pull
              - database_related_statistics
              - delta_sync
              - gsi_views
              - security_related_statistics
              - shared_bucket_import
              - per_replication statistics for each `replication_id`
            items:
              type: object
              properties:

                cache:
                  type: object

                database:
                  type: object

                per_replication:
                  type: array

                security:
                  type: object

          per_replication:
            type: array
            # summary: Per Replication Statistics (Deprecated)
            description: |+
              An array of stats for each replication declared in the config file

              **Deprecated @ 2.8**: used only by inter-sync-gateway replications version 1.
            items:
              type: object
              description: Stats for a given replication_id
              properties:
                $replication_id:
                  type: object
                  properties:
                    sgr_active:
                      type: boolean
                      description: |+
                        Whether the replication is active at this time.
                        **Deprecated @ 2.8**: used only by inter-sync-gateway replications version 1.
                    sgr_docs_checked_sent:
                      type: integer
                      description: |+
                        The total number of documents checked for changes since replication started.
                        This represents the number of potential change notifications pushed by Sync Gateway.
                        **Constraints**
                          This is not necessarily the number of documents pushed, as a given target might already have the change.
                          Used by versions 1 and 2.
                    sgr_num_attachments_transferred:
                      type: integer
                      description: |+
                        The total number of attachments transferred since replication started.
                        **Deprecated @ 2.8**: used only by inter-sync-gateway replications version 1.
                    sgr_num_attachment_bytes_transferred:
                      type: integer
                      description: |+
                        The total number of attachment bytes transferred since replication started.
                        **Deprecated @ 2.8**: used only by inter-sync-gateway replications version 1.
                    sgr_num_docs_failed_to_push:
                      type: integer
                      description: |+
                        The total number of documents that failed to be pushed since replication started.
                        Used by versions 1 and 2.
                    sgr_num_docs_pushed:
                      type: integer
                      description: |+
                        The total number of documents that were pushed since replication started.
                        Used by versions 1 and 2.
  Forbidden:
    type: object
    properties:
      error:
        type: string
        default: conflict
      id:
        type: string
      reason:
        type: string
      status:
        type: integer
        default: 409
  LogTags:
    type: object
    properties:
      Access:
        type: boolean
        description: access() calls made by the sync function
      Attach:
        type: boolean
        description: Attachment processing
      Auth:
        type: boolean
        description: Authentication
      Bucket:
        type: boolean
        description: Sync Gateway interactions with the bucket (verbose logging).
      Cache:
        type: boolean
        description: Interactions with Sync Gateway's in-memory channel cache (Cache+ for verbose logging)
      Changes:
        type: boolean
        description: Processing of _changes requests (Changes+ for verbose logging)
      CRUD:
        type: boolean
        description: Updates made by Sync Gateway to documents (CRUD+ for verbose logging)
      DCP:
        type: boolean
        description: DCP-feed processing (verbose logging)
      Events:
        type: boolean
        description: Event processing (webhooks) (Events+ for verbose logging)
      Feed:
        type: boolean
        description: Server-feed processing (Feed+ for verbose logging)
      HTTP:
        type: boolean
        description: All requests made to the Sync Gateway REST APIs (Sync and Admin). Note that the log keyword HTTP is always enabled, which means that HTTP requests and error responses are always logged (in a non-verbose manner). HTTP+ provides more verbose HTTP logging.
  PurgeBody:
    type: object
    description: Document ID
    properties:
      a_doc_id:
        type: array
        description: Only possible value is `["*"]`. It permanently removes all revisions for that document ID.
        items:
          type: string
          description: Only possible value is `"*"`. It permanently removes all revisions for that document ID.
          enum: ["*"]
  BulkDocsSuccess:
    type: object
    properties:
      id:
        type: string
        description: Design document identifier
      rev:
        type: string
        description: Revision identifier

  ChangesFeedRow:
    type: object
    properties:
      changes:
        type: array
        description: List of the document's leafs. Each leaf object contains one field, rev.
        items:
          type: object
          properties:
            rev:
              type: string
              description: Identifier of the document revision that changed.
      id:
        type: string
        description: Document identifier
      seq:
        type: integer
        description: Update sequence number

  QueryRow:
    type: object
    properties:
      id:
        type: string
        description: The ID of the document.
      key:
        type: object
        description: The key in the output row.
      value:
        type: object
        description: The value in the output row.
      doc:
        type: object
        description: The document body. This is only returned if `include_docs=true` is specified in the URL.

  Design:
    type: object
    properties:
      offset:
        type: integer
        format: int32
        description: Position in pagination.
      limit:
        type: integer
        format: int32
        description: Number of items to retrieve (100 max).
      count:
        type: integer
        format: int32
        description: Total number of items available.
  AllDocs:
    type: object
    properties:
      keys:
        type: array
        description: List of identifiers of the documents to retrieve
        items:
          type: string
          description: Document ID
  Changes:
    type: object
    properties:
      last_seq:
        type: object
        description: Last change sequence number
      results:
        type: array
        description: List of changes to the database. See the following table for a list of fields in this object.
        items:
          $ref: '#/definitions/ChangesFeedRow'


  Compact_Response:
    type: object
    description: JSON Respponse to a _compact request
    properties:
      status:
        type: string
        description: State of the _compact process (Running, Stopped, Completed)
      start_time:
        type: string
        description: |+
          Time the _compact process started for example "2015-09-23T17:27:17.55+01:00"
      end_time:
        type: string
        description: |+
          Time the _compact process ended for example "2015-09-23T17:27:17.55+01:00"
      last_error:
        type: string
        description: Text of the last error message.
      marked_attachments:
        type: integer
        description: The number of attachments marked during the ``mark``` phase.
      purged_attachments:
        type: integer
        description: The number of attachments purged by the ```sweep``` phase of the _compact process.
      compact_id:
        type: string
        description:  Unique identifier
      phase:
        type: string
        description:  |+
          This item indicates the current phase of `running` compact processes.
          It can be useful in monitoring progress.

          For failed processes, this indicates the phase at which a compact_id restart will commence (where relevant).

          Phases include:
          - mark
          - sweep
          - cleanup

  Document_model:
    type: object
    properties:
      _id:
        type: string
        description: The document ID.
      _rev:
        type: string
        description: Revision identifier of the parent revision the new one should replace. (Not used when creating a new document.)
      _exp:
        type: string
        description: |+
          Expiry time after which the document will be purged.

          The expiration time is set and managed on the Couchbase Server document (TTL is not supported for databases in walrus mode).

          The value can be specified in two ways; in ISO-8601 format, for example the 6th of July 2016 at 17:00 in the BST timezone would be 2016-07-06T17:00:00+01:00; it can also be specified as a numeric Couchbase Server expiry value.

          Couchbase Server expiries are specified as Unix time, and if the desired TTL is below 30 days then it can also represent an interval in seconds from the current time (for example, a value of 5 will remove the document 5 seconds after it is written to Couchbase Server).

          The document expiration time is returned in the response of GET /{db}/{doc} when show_exp=true is included in the querystring.

          As with the existing explicit purge mechanism, this applies only to the local database; it has nothing to do with replication.

          This expiration time is not propagated when the document is replicated.

          The purge of the document does not cause it to be deleted on any other database.
      _revisions:
        type: object
        properties:
          start:
            type: integer
            description: Prefix number for the latest revision.
          ids:
            type: array
            description: Array of valid revision IDs, in reverse order (latest first).
            items:
              type: string
              description: A revision ID.
      _attachments:
        type: array
        description: Array of attachments
        items:
          type: object
          properties:
            attachment_name:
                type: object
                properties:
                  ver:
                    type: integer
                    description: |
                      Indicate that the attachment reference is made through the new reference scheme (not exposed).
                      Value = 2.
                  content_type:
                    type: string
                    description: The content type of the attachment.
                  digest:
                    type: string
                    description: |+
                      Reference to stored attachment content
                  length:
                    type: integer
                  revpos:
                    type: integer
                  stub:
                    type: boolean
                    default: true

  doc-resp:
    type: object
    properties:
      id:
        type: string
        description: Document identifier
      rev:
        type: string
        description: Revision identifier
      ok:
        type: boolean
        description: Indicates whether the operation was successful

  QueryResult:
    type: object
    properties:
      offset:
        type: string
        description: Starting index of the returned rows.
      rows:
        type: array
        items:
          $ref: '#/definitions/QueryRow'
      total_rows:
        type: integer
        description: |+
          Number of documents in the database.
          This number is not the number of rows returned.

  ReplicationResponse:
    type: object
    properties:
      ok:
        type: boolean
        description: Indicates whether the replication operation was successful
      session_id:
        type: string
        description: Session identifier

  Replication_model:
    type: object
    title: "Replication Model"
    description: "Data schema for the replication model"
    properties:
      adhoc:
        type: boolean
        default: false
        description: |
          "
          **About**

          Use the Admin REST API's `adhoc` parameter to specify that a replication is ad hoc rather than persistent.

          **Behavior**

          Ad hoc replications behave the same as normal replications, but they are automatically removed when their status changes to stopped.
          This will usually be on completion, but may also be as a result of user action.

          **Constraints**

          This parameter is **NOT** available to configured replications; only those initialized using the Admin REST API."
      batch_size:
        type: integer
        default: 200
        description: |+
          **About**

          Use the optional `batch_size` property to specify the number of changes to be included in a single batch during replication.
      cancel:
        type: boolean
        default: false
        description: |+
          **About**

          Use this parameter on,y when you want to want to cancel an existing active replication.

          **Constraints**

          - This parameter is **NOT** available in configured replications; only those initialized using the Admin REST API.

          - **NOTE** that the body of the request must be the same as the replication's replication definition for the cancellation request to be honoured.
          For example, if you requested continuous replication, the cancellation request must also contain the continuous field.
      conflict_resolution_type:
        type: string
        default: default
        description: |+
          **About**

          The **`conflict_resolution_type`** property defines the conflict resolution policy that Sync Gateway applies when resolving conflicting revisions.

          The default behavior is that automatic conflict resolution policy is applied.

          **Valid options**
            - `default`
            - `localWins`
            - `remoteWins`
            - `custom`

          **Behavior**

          - *default* - Selecting `default` applies the following conflict resolution policy
            - Deletes always win (the delete with longest revision history wins if both revisions are deletes)
            - The revision with the longest revision history wins (so, the one with most changes and consequently the highest revision Id).

          - *localWins* - Selecting `localWins` will result in local revisions always being the winner in any conflict.
          - *remoteWins* - Selecting `remoteWins` will result in remote revisions always being the winner in any conflict.


          - *custom* - Selecting `custom` specifies that you want to handle conflict resolution with your own application logic. You **must** provide this logic as a Javascript function by specifying it in using the custom-conflict-resolver parameter.

          **Example**
          ```
          "conflict_resolution_type":"remoteWins"
          ```

          **Constraints**

          - Replications created prior to version 2.8 will default to `default`.
      continuous:
        type: boolean
        default: false
        description: |+
          **About**

          The `continuous` property specifies whether this replication will run in continuous mode.

          **Behavior**

          - `continuous=true`-- In continuous mode, changes are immediately synced in accordance with the replication definition.
          - `continuous=false`-- Detected changes are synced in accordance with the replication definition. The replication ceases once all revisions are processed.

          **Constraints**

          - Optional for stops and removes
      custom_conflict_resolver:
        type: string
        default: none
        description: |+
          **About**

          The optional `custom_conflict_resolver` property specifies the Javascript function that will be used to resolve conflicts, if the custom conflict resolution type is specified in the `conflict_resolution_type`.

          **Options**

          The property is *mandatory* when `conflict_resolution_type=custom` and will be ignored in all other cases.

          **Using**

          Provide the required logic in a Javascript function, as a string within backticks (see also the description for the `sync` function`.

          The function takes one parameter `struct` representing the conflict and comprising
          - the document id
          - the local document
          - the remote document

          The function returns a document `struct` representing the winning revision.

          **Example**
          ```
          "custom_conflict_resolver":`
            function(conflict) {
              console.log("full remoteDoc doc: "+JSON.stringify(conflict.RemoteDocument));
            return conflict.RemoteDocument;
          }`
          ```

          **Constraints**

          Using complex `custom_conflict_resolver` functions can noticeably degrade performance. Use a built-in resolver whenever possible.
      direction:
        type: string
        description: |+
          **About**

          The mandatory `direction` property specifies whether the replication is *push*, *pull* or *pushAndPull* relative to this node.

          The property value is referenced by the [remote](rest-api-admin.html#database-this_db-replications-remote) property.

          **Behavior**

          - `pull` - changes are pulled from the `remote` database
          - `push` - changes are pushed to the `remote` database
          - `pushAndPull` - changes are both pushed-to and pulled-from the `remote` database

          **Constraints**

          Replications created prior to version 2.8 derive their *direction* from the source/target url of the replication.
      enable_delta_sync:
        type: boolean
        default: false
        description: |+
          **About**

          The optional `enable_delta_sync` parameter turns on delta sync for a replication.
          It works in conjunction with the database level setting `delta_sync.enabled`.

          **Options**

          - `"enable_delta_sync": true`, the replication can use delta sync (depending on `delta_sync.enabled` setting)
          - `"enable_delta_sync": false`, the replication cannot use delta sync

          **Behavior**

          The optional `enable_delta_sync` parameter works in conjunction with the database level `delta_sync.enabled` setting, to determine whether this replication uses delta sync.

          - **If** `"delta_sync.enabled": true` for both databases involved in the replication, then this parameter enables or disables its use for this specific replication.
          -  In all other cases it has no effect and the replication runs without delta-sync.

          **Constraints**

          - Applies **ONLY** to Enterprise Edition deployments.
          - Depends upon the setting of the database level parameter `delta_sync.enabled`
          - Replications created prior to version 2.8 must run with `"enable_delta_sync": false`
          - Push replications will not use Delta Sync when pushing to a pre-2.8 target
      filter:
        type: string
        description: |+
          **About**

          Use the optional `filter`property to defines the function to be used to filter documents.

          **Options**

          A common value used when replicating from Sync Gateway is `sync_gateway/bychannel`.
          This option limits the pull replication to a specific set of channels.
          You can specify the required channels using `query_params`.

          **Behavior**

          Works in conjunction with `query_params` to control the documents processed by the replication.

          **Example**

          ```
          "filter":"sync_gateway/bychannel"
          ```

          **Constraints**

          OPTIONAL for stops and removes (even if defined during creation)
      max_backoff_time:
        type: integer
        default: 5
        description: |+
          The **max_backoff_time**property specifies the time-period (in minutes) during which Sync Gateway will attempt to reconnect lost or unreachable *remote* targets.

          On disconnection, Sync Gateway will do an exponential backoff up to the specified value, after which it will attempt to reconnect indefinitely every *max_backoff_time* minutes.

          If a zero value is specified, then Sync Gateway will do an exponential backoff up to an interval of five minutes before stopping the replication.

          NOTE - this value defaults to five minutes for replications created prior to version 2.8.
      password:
        type: string
        default: mandatory
        description: |+
          **About**

            Use `password` to provide the login password value for the accredited user running this replication.

          **Behavior**

            These details are used to authenticate credentials and approve access to data.

            Once provided and recorded, the password data is redacted and will not be displayed in either the configuration file or Admin REST API. A string of `****` will be displayed in its place.
      # perf_tuning_params:
        # type: object
        # description: |+
        #   The perf_tuning_params are not available in this release.

        #   NOTE - This property replaces the 'changes_feed_limit' at version 2.8
      purge_on_removal:
        type: boolean
        default: false
        description: |+
          **About**

          The optional `purge_on_removal` property specifies, per replication, whether the removal of a `channel` triggers a purge.

          **Options**
          - `true` or `false`
          - Default = false - Document removals are ignored by receiving end

          **Behavior**

          If `purge_on_removal=false`, then the removal of channels is ignored (not purged) by the receiving end.

          **Constraints**

          - Applies only to PULL replications, including the PULL portion of a PUSHANDPULL replication.

          - Replications created prior to version 2.8 *must* be run with `purge_on_removal=false`.
      query_params:
        type: array
        description: |+
          **About**

          The `query_params` property defines a set of key/value pairs used in the query string of the replication.

          **Behavior**

          This property works in conjunction with `filters` and `channels` to provide routing.

          **Using**

          You can use `query_params`' *channels* function to *pull* from a specific set of `channels`.
          To do so, you would also need to set the `filter` to  `sync_gateway/bychannels`.

          **Example**

          ```json
            "filter":"sync_gateway/bychannel",
            "query_params": {
              "channels":["channel.user1"]
            },
          ```

          **Constraints**

          OPTIONAL for stops and removes (even if defined during creation)
        items:
          type: string
      remote:
        type: string
        description: |+
          **About**

          The **remote** property represents the endpoint of a database for the remote Sync Gateway.
          That is, it identifies the remote Sync Gateway database that is the subject of this replication's push, pull or pushAndPull action.

          Typically the endpoint will include URI, Port and Database name elements.

          You can also include user credentials in the URL, in the form ```<username>:<password>```.
          The credentials relate to an existing Sync Gateway user on the remote server.

          **Example**
          ``` "remote": "http://user:password@example.com:4985/db1-remote"```


          **Format**

          - a string containing a valid URL for a (remote) Sync Gateway database.
          - an object whose url property contains the Sync Gateway database URL.

          **Behavior**

            Dependent upon setting of **direction**.

            If **direction** is :
            - *pull*, 'remote' defines the remote cluster *from* which data is pulled
            - *push*, 'remote' defines the remote cluster *to* which data is pushed
            - *pushAndPull*, 'remote' defines the *push* configuration.

          **Example**

          ```json
          "remote": "http://www.example.com:4984/sample-database",
          ```
      replication_id:
        type: string
        description: |+
          **About**

          The *replication_id* property specifies either:

          - For NEW replications, the ID to be assigned to the the replication.
          If no *replication_id* is specified, Sync Gateway will assign a random UUID to new replications.

          - For existing replications, this is the ID of the required replication.

          - If **cancel=true**, this is the id of the active replication task to be cancelled.

          **Constraints**

          If this is specified in the body of a POST or PUT request then it must be the same value as specified in the request URL.
      initial_state:
        type: string
        default: Running
        description: |+
          **About**

          The optional `initial_state` property is used to specify that the replication must be launched in 'Stopped' mode

          **Behavior**

          All replications are configured to start on Sync Gateway launch. So, if omitted, the state defaults to 'Running'.

          **Constraints*

          Replications created prior to version 2.8 will all default to a state of 'Running'.
      username:
        type: string
        default: Mandatory
        description: |+
          **About**

          Use `username` to provide the name of the accredited user running this replication.

          **Behavior**

          These details are used to authenticate credentials and approve access to data

          Once provided and recorded, the username data is redacted and will not be displayed in either the configuration file or Admin REST API. A string of `****` will be displayed in its place.

  # REPLICATIONSTATUS new at 2.8
  ReplicationStatusResponseBody:
    type: object
    properties:
      replication_id:
        type: string
        description: The replication Id.
      docs_read:
        type: integer
        description: The number of docs that have been read (fetched) from the source database.
      docs_written:
        type: integer
        description: The number of docs that have been written (pushed) to the target database.
      docs_purged:
        type: integer
        description: The number of docs that have been purged.
      doc_write_failures:
        type: integer
        description: |+
          The number of docs that have failed to be written (pushed) to the target database.
          These docs will not be retried.
      doc_write_conflict:
        type: integer
        description: The number of docs that were in conflict.
      status:
        type: string
        description: |+
          The status of the replication.

          Valid values are:
          - Starting
          - Started
          - Stopping
          - Stopped
          - Error
      rejected_by_remote:
        type: integer
        description: Count of documents that were sent to the remote but did not get replicated because they were rejected by the sync function on the remote
      rejected_by_local:
        type: integer
        description: Count of documents that were received by the local but did not get replicated because they were rejected by the sync function on the local
      last_seq_pull:
        type: string
        description: |+
          Last sequence number processed in pull replication.

          The last_seq_pull result can be used by apps to determine if a specific document has been synced to target or not.

          To do this, query the **_raw** endpoint and compare the sequence number of the document with the last_seq value (push or pull as approperiate) replicated.
      last_seq_push:
        type: string
        description: |+
          Last sequence value processed in push replication.

          The last_seq_push result can be used by apps to determine if a specific document has been synced to target or not.

          To do this, query the **_raw** endpoint and compare the sequence number of the document with the last_seq value (push or pull as approperiate) replicated.
      error_message:
        type: string
        description: |+
          A message describing the reason for the latest error.
          It is reset each Sync Gateway restart.
      delta_sent:
        type: integer
        description: |+
          This is the number of deltas sent.

          Whether or not deltas are sent and-or received is based on whether the remote:

          - has deltas enabled, and-or

          - can generate a delta for the requested revision.

      delta_recv:
        type: integer
        description: The number of delta-sync changes sent
      delta_requested:
        type: integer
        description: |+
          The number of delta-sync changes requested.

          This should always be non-zero when delta_sync.enabled is true.
      config:
        type: object
        description: |+
          This optional response content is returned only when using the {querystring} option with `includeConfig=true`. For example,

          ```
          GET http://localhost:4985/db-local/_replicationStatus?includeError=true&includeConfig=true
          ```

          It comprises the replication definition as would be returned using a `GET` request to the  `_replication` endpoint.

  Resync-response:
    type: object
    properties:
      status:
        type: string
        description: |+
          Indicates the status of the resync operation.

          Possible values:

          - running,

          - stopped,

          - stopping,

          - stopped on error

      start_time:
        type: string
        description: |+
          The `_resync` process start time in ISO 8601 format (for example: `2012-04-23T18:25:43.511Z`)


      docs_changed:
        type: integer
        description: |+
          Shows the number of documents that have been changed as a result of the sync function.

          Docs are only changed if when run through the new sync function the resulting doc is different to the currently stored doc.
      docs_procesed:
        type: integer
        description: |+
          Shows the number of documents that have been run through the sync function.

      last_error:
        type: string
        description: |+
          Will ONLY be present when status = “stopped on error”

          In the event of an error in the `_resync` process this field will contain error details.
          Otherwise it is not visible.

  Server:
    type: object
    properties:
      couchdb:
        type: string
        description: Contains the string 'Welcome' (this is required for compatibility with CouchDB)
      vendor/name:
        type: string
        description: The server type ('Couchbase Sync Gateway)
      vendor/version:
        type: string
        description: The server version
      version:
        type: string
        description: Sync Gateway version number

  ReplicationResponseBody:
    type: object
    description: This is the replication definition set returned in response to a `GET` request.
    properties:
      this_rep:
        type: object
        description: This is the replication definition set returned in response to a `GET` request.
        properties:
          adhoc:
            type: boolean
            default: false
            description: |+
              Indicates whether this replication is ad hoc (`"adhoc": true`) or Persistent.
              Both replications behave in the same way, except that **adhoc** replications are automatically removed when their status changes to **stopped**.
              This will usually be on completion, but may also be as a result of user action).

          batch_size:
            type: integer
            default: 200
            description: |+
              **About**

              The `batch_size` property specifies the number of changes to be included in a single batch during replication.

          conflict_resolution_type:
            type: string
            default: default
            description: |+
              **About**

              The **`conflict_resolution_type`** property specifies the conflict resolution policy Sync Gateway will apply when resolving conflicting revisions.

              The default behavior is that automatic conflict resolution policy is applied.

              **Valid options**

                - `default`

                - `localWins`

                - `remoteWins`

                - `custom`

              **Behavior**

              - *default* - Selecting `default` applies the following conflict resolution policy

                - Deletes always win (the delete with longest revision history wins if both revisions are deletes)

                - The revision with the longest revision history wins (so, the one with most changes and consequently the highest revision Id).

              - *localWins* - Selecting `localWins` will result in local revisions always being the winner in any conflict.

              - *remoteWins* - Selecting `remoteWins` will result in remote revisions always being the winner in any conflict.


              - *custom* - Selecting `custom` specifies that you want to handle conflict resolution with your own application logic.
              You **must** provide this logic as a Javascript function by specifying it in using the custom-conflict-resolver parameter.

              **Example**
              ```
              "conflict_resolution_type":"remoteWins"
              ```

              **Constraints**

              - Replications created prior to version 2.8 will default to `default`.


          continuous:
            type: boolean
            default: false
            description: |+
              **About**

              The `continuous` property specifies whether this replication runs in continuous, or single-shot, mode.

              **Behavior**

              - `continuous=true`-- In continuous mode, changes are immediately synced in accordance with the replication definition.

              - `continuous=false`-- Detected changes are synced in accordance with the replication definition. The replication ceases once all revisions are processed.

              **Constraints**

              - Optional for stops and removes

          custom_conflict_resolver:
            type: string
            default: none
            description: |+
              **About**

              The `custom_conflict_resolver` property specifies the Javascript function that will be used to resolve conflicts, if the custom conflict resolution type is specified in the `conflict_resolution_type`.

              **Options**

              The property is *mandatory* when `conflict_resolution_type=custom` and will be ignored in all other cases.

              **Using**

              Provide the required logic in a Javascript function, as a string within backticks (see also the description for the `sync` function`.

              The function takes one parameter `struct` representing the conflict and comprising

              - the document id

              - the local document

              - the remote document

              The function returns a document `struct` representing the winning revision.

              **Example**
              ```
              "custom_conflict_resolver":`
                function(conflict) {
                  console.log("full remoteDoc doc: "+JSON.stringify(conflict.RemoteDocument));
                return conflict.RemoteDocument;
              }`
              ```

              **Constraints**

              Using complex `custom_conflict_resolver` functions can noticeably degrade performance. Use a built-in resolver whenever possible.


          direction:
            type: string
            description: |+
              **About**

              The mandatory `direction` property indicates whether the replication is *push*, *pull* or *pushAndPull*.

              The property value is referenced by the **remote** property.

              **Constraints**

              Replications created prior to version 2.8 derive the *direction* from the source/target url of the replication.


          enable_delta_sync:
            type: boolean
            default: false
            description: |+
              **About**

              The `enable_delta_sync` property specifies whether delta sync is, or is not, used for the replication.

              **Options**

              To use delta sync or not.

              - `enable_delta_sync=true` - the replication runs using delta sync

              - `enable_delta_sync=false` - the replication runs without delta sync

              **Behavior**

              The impact of this property is dependent on the `delta_sync.enabled` setting for the relevent databases as indicated here.

              - **If** `"delta_sync.enabled": true` for both databases involved in the replication, then this parameter enables or disables its use for this specific replication.

              - In all other cases it has no effect and the replication runs without delta-sync.

              **Constraints**

              - Requires *Enterprise Edition*
              - Replications created prior to version 2.8 run with `enable_delta_sync=false`


          filter:
            type: string
            description: |+
              **About**

              Use the optional `filter` property to defines the function to be used to filter documents.

              **Options**

              A common value used when replicating from Sync Gateway is `sync_gateway/bychannel`.
              This option limits the pull replication to a specific set of channels.
              You can specify the required channels using `query_params`.

              **Behavior**

              Works in conjunction with `query_params` to control the documents processed by the replication.

              **Example**

              ```
              "filter":"sync_gateway/bychannel"
              ```

              **Constraints**

              OPTIONAL for stops and removes (even if defined during creation)


          max_backoff_time:
            type: integer
            default: 5
            description: |+
              **About**

              The **max_backoff_time** property indicates the time-period (in minutes) during which Sync Gateway will attempt to reconnect lost or unreachable *remote* targets.

              On disconnection, Sync Gateway will do an exponential backoff up to the specified value, after which it will attempt to reconnect indefinitely every *max_backoff_time* minutes.

              If the value is zero, Sync Gateway will do an exponential backoff up to an interval of five minutes before stopping the replication.

              **Constrains**

              This value defaults to five minutes for replications created prior to version 2.8.


          password:
            type: string
            default: Mandatory
            description: |+
                The `password`, forms part of the login credentials used to access the data.

                All password data is redacted and is displayed as a string of `****`.

          perf_tuning_params:
            type: object
            description: |+
              The perf_tuning_params are yet to be defined (subject to performance testing)

              NOTE - This property replaces the 'changes_feed_limit' at version 2.8

          purge_on_removal:
            type: boolean
            default: false
            description: |+
              **About**

              The optional `purge_on_removal` property specifies, per replication, whether the removal of a `channel` triggers a purge.

              **Options**
              - `true` or `false`
              - Default = false - Document removals are ignored by receiving end

              **Behavior**

              If `purge_on_removal=false`, then the removal of channels is ignored (not purged) by the receiving end.

              **Constraints**

              - Applies only to PULL replications, including the PULL portion of a PUSHANDPULL replication.

              - Replications created prior to version 2.8 *must* be run with `purge_on_removal=false`.


          query_params:
            type: array
            description: |+
              **About**

              The `query_params` property defines a set of key/value pairs used in the query string of the replication.

              **Behavior**

              This property works in conjunction with `filters` and `channels` to provide routing.

              **Using**

              You can use `query_params`' *channels* function to *pull* from a specific set of `channels`.
              To do so, you would also need to set the `filter` to `sync_gateway/bychannels`.

              **Example**

              ```json
                "filter":"sync_gateway/bychannel",
                "query_params": {
                  "channels":["channel.user1"]
                },
              ```

              **Constraints**

              OPTIONAL for stops and removes (even if defined during creation)

            items:
              type: string

          remote:
            type: string
            description: |+
              **About**

              The **remote** property represents a database URL for the remote Sync Gateway.
              That is, it identifies the remote Sync Gateway database that is the subject of this replication's push, pull or pushAndPull action.

              **Behavior**

              Dependent upon setting of **direction**. If **direction** is :

              - *pull*, this is the cluster *from* which data is pulled

              - *push*, this is the cluster *to* which data is pushed

              - *pushAndPull*, this is the cluste from which data is pushed.

              **Example**

              ```
                "remote": "http://www.example.com:4984/db2name",
              ```

              **Constraints**

              - You must specify the 'remote' database's url even if it is located on the same cluster as the replication's database.

              - OPTIONAL for stops and removes


          replication_id:
            type: string
            description: |+
              **About**

              The *replication_id* property indicates the ID that Sync Gateway assigned to the replication.

              Sync Gateway assigns a random UUID if no `replication_id` is  specified when the replication is created.

          initial_state:
            type: string
            default: Running
            description: |+
              **About**

              The optional `initial_state` property is used to specify that the replication must be launched in 'Stopped' mode

              **Behavior**

              All replications are configured to start on Sync Gateway launch.
              So, if omitted, the state defaults to 'Running'.

              **Constraints*

              Replications created prior to version 2.8 will all default to a state of 'Running'.

          username:
            type: string
            default: Mandatory
            description: |+

                The `username` forms part of the credentials used to authenticate and approve access to data

                This field is redacted a string of '****' is displayed in its place.

  ReplicationStatistics-SGR1:

    description: This is the replication definition set returned in response to an ExpVars `GET` request.
    properties:
      replname:
        type: object
        description: |+
          This object comprises the stats collected and recorded for the inter-sync-gateway replication named $replname (which equates to a `replication_id`).

          The same structure is used to return statistics from inter-sync-gateway replications versions 1 and 2, but not all items are populated by each version.
        properties:
          sgr_active:
            type: boolean
            description: |+
              Whether the replication is active at this time.
              **Deprecated @ 2.8**: used only by inter-sync-gateway replications version 1.

          sgr_docs_checked_sent:
              type: integer
              description: |+
                The total number of documents checked for changes since replication started.

                This represents the number of potential change notifications pushed by Sync Gateway.

                **Constraints**
                - This is not necessarily the number of documents pushed, as a given target might already have the change.

                - Used by versions 1 and 2.

          sgr_num_attachments_transferred:
              type: integer
              description: |+
                The total number of attachments transferred since replication started.
                **Deprecated @ 2.8**: used only by inter-sync-gateway replications version 1.

          sgr_num_attachment_bytes_transferred:
              type: integer
              description: |+
                The total number of attachment bytes transferred since replication started.
                **Deprecated @ 2.8**: used only by inter-sync-gateway replications version 1.

          sgr_num_docs_failed_to_push:
              type: integer
              description: |+
                The total number of documents that failed to be pushed since replication started.

                Used by versions 1 and 2.
          sgr_num_docs_pushed:
              type: integer
              description: |+
                The total number of documents that were pushed since replication started.

                Used by versions 1 and 2.


  View:
    type: object
    properties:
      _rev:
        type: string
        description: Revision identifier of the parent revision the new one should replace. (Not used when creating a new document.)
      views:
        type: object
        description: List of views to save on this design document.
        properties:
          my_view_name:
            type: object
            description: The view's map/reduce functions.
            properties:
              map:
                type: string
                description: Inline JavaScript definition for the map function
              reduce:
                type: string
                description: Inline JavaScript definition for the reduce function



parameters:

  access:
    name: access
    in: query
    description: |+
      Indicates whether to include in the response a list of what access this document grants (i.e. which users it allows to access which channels.)
      This option may only be used from the admin port.
    type: boolean
    default: false

  active_only:
    name: active_only
    in: query
    description: |+
      Default is false.
      When true, the changes response doesn't include either deleted documents, or notification for documents that the user no longer has access to.
    type: boolean
    default: false

  attachment:
    in: path
    name: attachment
    description: |+
      Attachment name.
      This value must be URL encoded.
      For example, if the attachment name is `blob_/avatar`, the path component passed to the URL should be `blob_%2Favatar` (tested with [URLEncoder](https://www.urlencoder.org/)).
    type: string
    required: true

  atts_since:
    in: query
    name: atts_since
    description: |+
      Include attachments only since specified revisions.
      Does not include attachments for specified revisions.
    type: array
    items:
      type: string

  include_attachments:
    in: query
    name: attachments
    description: |+
      Include attachment bodies in response.
      Default is false.
    type: boolean
    default: false

  bootstrap-logging:
    name: bootstrap logging setting
    in: body
    required: true
    schema:
      $ref: '#/definitions/Logging_model'

  bulkget:
    in: body
    name: BulkGetBody
    description: |+
      List of documents being requested.

      Each array element is an object that must contain an id property giving the document ID.
      It may contain a rev property if a specific revision is desired.
      It may contain an atts_since property (as in a single-document GET) to limit which attachments are sent.
    schema:
      type: array
      items:
        type: object
        properties:
          id:
            type: string
            description: Document ID.
          att_since:
            type: string
            description: att_since
          rev:
            type: string
            description: rev

  channels:
    in: query
    name: channels
    description: |+
      Indicates whether to include in the response a channels property containing an array of channels this document is assigned to.
      Channels not accessible by the user making the request will not be listed.
    type: boolean
    default: false
  channels_list:
    in: query
    name: channels
    description: A comma-separated list of channel names. The response will be filtered to only documents in these channels. (This parameter must be used with the **sync_gateway/bychannel** filter parameter; see below.)
    type: string
    required: false

  compaction_action:
    type: string
    in: query
    name: action
    description: |+
      Use the ```action``` parameter to *start* or *stop* a `_compact` process.

      The value must be one of :
      - `start` - immediately starts (or restarts) a compaction and returns its status

      - `stop` -  immediately stops the active compaction and returns the status

      This parameter works in conjunction with compaction type.

    default: start

  compaction_dry_run:
    in: query
    type: string
    name: dry_run
    default: false
    description: |+
     Use ```dry_run``` only for attachment compaction.

     If this is set to ```true``` the process will run but will not execute the final purge of attachments.
     It can be used to check how many attachments will be purged.

  compaction_reset:
    in: query
    type: string
    name: reset
    default: false
    description: |+
     Use ```reset``` only for attachment compaction.

     If this is set to ```true``` the ```start``` action will not attempt to resume a failed process but will force a fresh compact to start.

  compaction_type:
    type: string
    in: query
    name: type
    description: |+
      Use the ```type``` option to specify the type of compaction required.

      The type must be one of :
      - `attachment` for legacy pre-3.0 attachment compaction

      - `tombstone` for database compaction, which purges the JSON bodies of non-leaf revisions.

      This parameter works in conjunction with compaction action.
    default: tombstone

  content_type:
    in: header
    name: Content-Type
    description: Attachment Content-Type
    type: string

  database_config_body:
    in: body
    name: 'database configuration details'
    description: |+
      Provision the database configuration details as JSON object in request body
    schema:
      $ref: '#/definitions/Database_model'

  db:
    name: db
    in: path
    description: Database name
    type: string
    required: true

  ddoc:
    name: ddoc
    in: path
    description: Design document name
    type: string
    required: true

  doc:
    name: doc
    in: path
    description: Document ID
    type: string
    required: true

  doc_ids:
    in: query
    name: doc_ids
    description: |+
      A list of document IDs as a valid JSON array.
      The response will be filtered to only documents with these IDs.
      This parameter must be used with the `filter=_doc_ids` and `feed=normal` parameters.
    type: array
    items:
      type: string

  endkey:
    name: endkey
    in: query
    description: If this parameter is provided, stop returning records when the specified key is reached.
    type: string
    required: false
  feed:
    in: query
    name: feed
    description: Default is 'normal'. Specifies type of change feed. Valid values are normal, continuous, longpoll, websocket.
    type: string
    default: 'normal'

  heartbeat:
    in: query
    name: heartbeat
    description: |+
      Default is 0. Interval in milliseconds at which an empty line (CRLF) is written to the response.

      This helps prevent gateways from deciding the socket is idle and closing it.
      Only applicable to longpoll or continuous feeds.
      Overrides any timeout to keep the feed alive indefinitely.
      Setting to 0 results in no heartbeat.
    type: integer
    default: 0
  include_docs:
    in: query
    name: include_docs
    description: |+
      Default is false.
      Indicates whether to include the associated document with each result.
      If there are conflicts, only the winning revision is returned.
    type: boolean
    default: false
  keys:
    in: query
    name: keys
    description: |+
      Specify a list of document IDs.
      Note that this is an array field, so to retrieve docs with Ids of "keyid1" and "keyid4", for example, use a request in this format --

      ```curl -X GET \ 'http://localhost:4985/test_db/_all_docs?keys=[%22keyid1%22,%22keyid4%22]' \ -H 'Accept: application/json'```
    type: array
    items:
      type: string


  limit:
    in: query
    name: limit
    description: Limits the number of result rows to the specified value. Using a value of 0 has the same effect as the value 1.
    type: integer
  local_doc:
    in: path
    name: local_doc
    description: Local document IDs begin with _local/.
    type: string
    required: true

  new_edits:
    name: new_edits
    in: query
    description: |+
      Default is true.
      Setting this to false indicates that the request body is an already-existing revision that should be directly inserted into the database, instead of a modification to apply to the current document. (This mode is used by the replicato.)

      This option must be used in conjunction with the `_revisions` property in the request body.
    type: boolean
    default: true

  open_revs:
    in: query
    name: open_revs
    description: |+
      Option to fetch specified revisions of the document.
      The value can be `all` to fetch all leaf revisions or an array of revision numbers (i.e. open_revs=["rev1", "rev2"]). Only [leaf revision](glossary.html) bodies that haven't been pruned are guaranteed to be returned.

      If this option is specified the response will be in multipart format.
      Use the `Accept: application/json` request header to get the result as a JSON object.
    type: string
    required: false

  replication__replication-body:
    in: body
    name: ReplicationBody
    # summary: Basic replication body (json)
    description: |+
      This replication request message body is a JSON document that comprises all the properties required to upsert a replication.

      If the `replicationID` matches an existing `replication_id` then the values of any properties provided in the body are used to update the existing replication's property values.
    schema:
      $ref: '#/definitions/Replication_model'


  import_filter_body:
    name: import_filter
    description: The Javascipt code for the import filter function
    in: body
    required: true
    schema:
      $ref: '#/definitions/Import_filter_model'


  role_body:
    in: body
    name: role
    description: The message body is a JSON document that contains the following objects.
    schema:
      $ref: '#/definitions/Role_model'

  sync_function_body:
    name: sync function
    description: The Javascipt code for the sync function
    in: body
    required: true
    schema:
      $ref: '#/definitions/Sync_model'


  replication_id-upsert:
    in: path
    type: string
    name: replicationID
    required: true
    description: |+
      If supplied, the <i>replicationID</i> parameter must be a valid replication id.

      If it is not supplied for a <i>new</i> replication*, then a random UUID is generated.


  replication_id-required:
    in: path
    type: string
    name: replicationID
    required: true
    description: |+
      The {replicationID} parameter identifies the target replication.

  replicationStatus-action:
    in: query
    name: action
    type: string
    default: none
    required: true
    description: |+
      The value of the {action} parameter specifies the value you want the selected replication's status set to.

      Valid values are:

      - **start** : Use this action to start a stopped replication

      - **stop** : Use this action to stop a started replication

      - **reset** : Use this action to reset a stopped replication.
      This will set the checkpoint to zero.
      For bidirectional replication, both push and pull checkpoints are reset to zero.

  resync-action:
    in: query
    name: action
    type: string
    default: "start"
    required: false
    description: |+
      The action query can be “start” or “stop”.
      If neither is provided,“start” is used as the default.

      - Start will 'begin' the asynchrounous resync operation.

      - Stop will stop the resync operation and will return

  resync-regenerate:
    in: query
    name: regenerate_sequences
    type: string
    default: none
    required: false
    description: |+
      **Use this only when requested to do so by the Couchbase support team**

      Set **```regenerate_sequences=true```** along with
      ```action=start``` in order to begin a resync while regenerating sequences.

  rev:
    name: rev
    in: query
    description: Revision identifier of the parent revision the new one should replace. (Not used when creating a new document.)
    type: string
    required: false
  rev_get:
    name: rev
    in: query
    description: |+
      Revision identifier of the revision to get.

      By default, Sync Gateway returns the current revision.
      This parameter is generally only needed for conflict resolution.
      For example where the app might need to retrieve a conflicting leaf revision that isn't the current revision.
    type: string
    required: false
  rev_put:
    name: rev
    in: query
    description: Revision identifier of the revision to update. It must be the last revision in the history.
    type: string
    required: true
  rev_delete:
    name: rev
    in: query
    description: Revision identifier of the revision to delete. It must be the identifier of the latest revision in the history.
    type: string
    required: true

  revs:
    in: query
    name: revs
    description: |+
      Default is false.
      Indicates whether to include a _revisions property for each document in the response, which contains a revision history of the document.
      The length of the returned revision tree can be specified with the `revs_limit` querystring parameter.
    type: boolean
    default: false


  role_name:
    in: path
    name: name
    description: |+
      Role name, may contain any combination of the characters `[a-z A-Z 0-9 - + . @ %]`, when creating a role any other characters must be percent encoded, see:
      [https://en.wikipedia.org/wiki/Percent-encoding](https://en.wikipedia.org/wiki/Percent-encoding).

      When passing a role name in a URL path it must be escaped again using percent encoding for example if a role is created with the name "0|59", the '|' character must first be percent-encoded resulting in "0%7C59". When using the same role name in a URL path it must be percent-encoded a second time resulting in "0%257C59"
    type: string
    required: true
  sessionid:
    name: sessionid
    in: path
    description: Session id
    type: string
    required: true
  startkey:
    name: startkey
    in: query
    description: Returns records starting with the specified key.
    type: string
    required: false
  since:
    in: query
    name: since
    description: |+
      Starts the results from the change immediately after the given sequence ID.

      Sequence IDs should be considered opaque; they come from the last_seq property of a prior response.
    type: integer
    required: false
  style:
    in: query
    name: style
    description: |+
      Default is 'main_only'.
      Number of revisions to return in the changes array.
      main_only returns the current winning revision, all_docs returns all leaf revisions including conflicts and deleted former conflicts.
    type: string
    default: 'main_only'
  timeout:
    in: query
    name: timeout
    description: |+
      Default is 300000.
      Maximum period in milliseconds to wait for a change before the response is sent, even if there are no results.
      Only applicable for longpoll or continuous feeds.
      Setting to 0 results in no timeout.
    type: integer
    default: 300000
  update_seq:
    in: query
    name: update_seq
    description: Default is false. Indicates whether to include the update_seq (document sequence ID) property in the response.
    type: boolean
    default: false
  view:
    name: view
    in: path
    description: View name
    type: string
    required: true
  bulkdocs:
    in: body
    name: BulkDocsBody
    description: The request body
    schema:
      properties:
        docs:
          type: array
          description: List containing new or updated documents. Each object in the array can contain the following properties _id, _rev, _deleted, and values for new and updated documents.

          items:
            type: object
            $ref: '#/definitions/Document_model'
        new_edits:
          description: Indicates whether to assign new revision identifiers to new edits.
          type: boolean
          default: true
  batch:
    in: query
    name: batch
    description: Stores the document in batch mode. To use, set the value to ok.
    type: string
    required: false
  changes_body:
    in: body
    name: ChangesBody
    description: The request body
    schema:
      properties:
        limit:
          description: Limits the number of result rows to the specified value. Using a value of 0 has the same effect as the value 1.
          type: integer
        style:
          description: Default is 'main_only'. Number of revisions to return in the changes array. The only possible value is all_docs and it returns all leaf revisions including conflicts and deleted former conflicts.
          type: string
          default: 'main_only'
        active_only:
          description: Default is false. When true, the changes response doesn't include either deleted documents, or notification for documents that the user no longer has access to.
          type: boolean
          default: false
        include_docs:
          description: Default is false. Indicates whether to include the associated document with each result. If there are conflicts, only the winning revision is returned.
          type: boolean
          default: false
        filter:
          description: Indicates that the returned documents should be filtered. The valid values are sync_gateway/bychannel and _doc_ids.
          type: string
        channels:
          description: A comma-separated list of channel names. The response will be filtered to only documents in these channels. (This parameter must be used with the sync_gateway/bychannel filter parameter; see below.)
          type: string

        doc_ids:
          type: array
          description: A list of document IDs as a valid JSON array. The response will be filtered to only documents with these IDs. (This parameter must be used with the _doc_ids filter parameter; see below.)

          items:
            type: string
        feed:
          description: Default is 'normal'. Specifies type of change feed. Valid values are normal, continuous, longpoll, websocket.
          type: string
          default: 'normal'
        since:
          description: Starts the results from the change immediately after the given sequence ID. Sequence IDs should be considered opaque; they come from the last_seq property of a prior response.
          type: object
        heartbeat:
          description: Default is 0. Interval in milliseconds at which an empty line (CRLF) is written to the response. This helps prevent gateways from deciding the socket is idle and closing it. Only applicable to longpoll or continuous feeds. Overrides any timeout to keep the feed alive indefinitely. Setting to 0 results in no heartbeat.
          type: integer
          default: 0
        timeout:
          description: Default is 300000. Maximum period in milliseconds to wait for a change before the response is sent, even if there are no results. Only applicable for longpoll or continuous feeds. Setting to 0 results in no timeout.
          type: integer
          default: 300000
  filter:
    in: query
    name: filter
    description: Indicates that the reported documents should be filtered. The valid values are sync_gateway/bychannel and _doc_ids.
    type: string
    required: false
  logtags:
    in: body
    name: log_keys
    description: |+
      Use the body to provide a list of the log keys you want to set.

      For example - `{"Changes++":true, "Cache":true, "HTTP":true, "DCP":true, "WS": true, "WSFrame": true, "Replicate": true}`
    schema:
      type: object
      properties:
        All:
          type: boolean
          description: |+
            Use the wildcard character `*` to set all log keys
            For example ```{"*":true}```
        none:
          type: boolean
          description: |+
            Use "none" or "" as the key to disable all log keys.
            For example ```{"none":true}```
        Admin:
          type: boolean
          description: Admin processes in Sync Gateway.
        Access:
          type: boolean
          description: Anytime an access() call is made in the sync function.
        Auth:
          type: boolean
          description: Authentication.
        Bucket:
          type: boolean
          description: Sync Gateway interactions with the bucket (trace level only).
        Cache:
          type: boolean
          description: Interactions with Sync Gateway's in-memory channel cache.
        Changes:
          type: boolean
          description: Processing of /{db}/_changes requests.
        CRUD:
          type: boolean
          description: Updates made by Sync Gateway to documents.
        DCP:
          type: boolean
          description: DCP-feed processing.
        Events:
          type: boolean
          description: Event processing (webhooks).
        gocb:
          type: boolean
          description: All logging emitted by the GoCB SDK
        HTTP:
          type: boolean
          description: All requests made to the Sync Gateway REST APIs.
        HTTP+:
          type: boolean
          description: Additional information about HTTP requests (response times, status codes).
        Import:
          type: boolean
          description: Introduced in Sync Gateway 1.5 to help troubleshoot the import process of a document (this is the Sync Gateway process to make a document that was added through N1QL or the Server SDKs mobile-aware). This log key can be useful to troubleshoot why a given document was not successfully imported.
        Javascript:
          type: boolean
          description: All logging from Javascript. This includes - sync function, import filters, webhook filter function, and the custom ISGR conflict resolvers
        Migrate:
          type: boolean
          description: Logs messages thhat show when old inline document metdata is upgraded to xattrs
        Query:
          type: boolean
          description: Query is used for Sync Gateway code related to N1QL queries
        Replicate:
          type: boolean
          description: |+
            Log messages related to replications between Sync Gateways (using sg-replicate). This tag cannot be used for replications initiated by Couchbase Lite.
        SGCluster:
          type: boolean
          description: Log messages related to the sharded import and HA sg-replicate
        Sync:
          type: boolean
          description: Activity which relates to synchronization between Couchbase Lite and Sync Gateway
        SyncMsg:
          type: boolean
          description: Can be used for additional Sync logging output
        WS:
          type: boolean
          description: Websocket replication log messages
        WSFrame:
          type: boolean
          description: Can be used for additional WS logging output
  level:
    in: query
    name: level
    description: |+
      **Deprecated** - please use `logLevel` instead
      This setting determines the verbosity of the logging
      - level=1 - The default, regular, logging
      - level=2 - Enables warnings and panics logging
      - level=3 - Will log panics only
    type: integer
  logLevel:
    in: query
    name: logLevel
    description: |+
      This setting determines the verbosity of the logging.

      Available values are
      - `none`
      - `error`
      - `warn`
      - `info`
      - `debug`
      - `trace`

      Note that the setting is additive. For example, setting `info` will also enable both `error` and `warn`.

    type: string
  sgcollect_info:
    in: body
    name: sgcollect_info
    description: Options that can be specified to use in an sgcollect_info run
    schema:
      type: object
      properties:
        redact_level:
          type: string
          description: Can be set to `none` or `partial` for redaction of collected logs.
          default: none
        redact_salt:
          type: string
          description: If set, use this salt when redacting logs.
        output_dir:
          type: string
          description: Where to store the collected zip.
          default: configured `LogFilePath` location (for example `/home/sync_gateway/logs`)
        upload:
          type: boolean
          description: Whether to upload the collected logs.
          default: false
        upload_host:
          type: string
          description: s3 URL for upload.
          default: https://uploads.couchbase.com
        customer:
          type: string
          description: |+
            Customer name to use when uploading logs.
            required - if upload is set
        ticket:
          type: string
          description: Zendesk ticket number to use when uploading logs.

  name:
    in: path
    name: name
    description: |+
      User's name, may contain contain any combination of the characters `[a-z A-Z 0-9 - + . @ %]`, when creating a user any other characters must be percent encoded, see: [https://en.wikipedia.org/wiki/Percent-encoding](https://en.wikipedia.org/wiki/Percent-encoding).

      When passing a user name in a URL path it must be escaped again using percent encoding for example if a user is created with the name "0|59", the '|' character must first be percent-encoded resulting in "0%7C59". When using the same user name in a URL path it must be percent-encoded a second time resulting in "0%257C59"
    type: string
    required: true

  replicate__replication-body:
    in: body
    name: ReplicationBody
    description: |+
      SGR1 replication
      The request message body is a JSON document that contains the following objects.
    schema:
      type: object
      properties:
        source:
          type: string
          description: Identifies the database to copy revisions from. Can be a string containing a local database name or a remote database URL, or an object whose url property contains the database name or URL. Also an object can contain headers property that contains custom header values such as a cookie.
        target:
          type: string
          description: Identifies the database to copy revisions to. Same format and interpretation as source.
        continuous:
          type: boolean
          description: Specifies whether the replication should be in continuous mode.
        filter:
          type: string
          description: Indicates that the documents should be filtered using the specified filter function name. A common value used when replicating from Sync Gateway is sync_gateway/bychannel to limit the pull replication to a set of channels.
        query_params:
          type: object
          description: A set of key/value pairs to use in the querystring of the replication. For example, the channels field can be used to pull from a set of channels (in this particular case, the filter key must be set for the channels field to work as expected).
        replication_id:
          type: string
          description: If the cancel parameter is true then this is the id of the active replication task to be cancelled, otherwise this is the replication_id to be used for the new replication. If no replication_id is given for a new replication it will be assigned a random UUID.

        cancel:
          type: boolean
          description: Indicates that a running replication task should be cancelled, the running task is identified by passing its replication_id or by passing the original source and target values.
        changes_feed_limit:
          type: integer
          description: The maximum number of change entries to pull in each loop of a continuous changes feed.
          default: 50
  revs_limit:
    in: query
    name: revs_limit
    description: |+
      The number of revisions to include in the response from the document history.

      This property is only honoured if `revs=true` is also sent in the request.

      If `revs=true` is specified and `revs_limit` isn't, the full revision history is returned.

      For more information see: [Revisions](revisions.html) page.
    type: integer
    required: false
  show_exp:
    in: query
    name: show_exp
    description: Whether to show the _exp property in the response.
    type: boolean
    default: false
    required: false

  user_body:
    in: body
    name: user configuration data
    description: Provision the user configuration data in JSON format in the body
    schema:
      $ref: '#/definitions/User_model'

  upgrade_preview:
    in: query
    name: preview
    description: Lists the design documents to be removed if the request is sent without this paramter.
    type: boolean
    default: false
    required: false


tags:
  # - name: attachment
  #   description: Groups all endpoints for attachment activities
  - name: Authentication
    description: Manage OpenID Connect providers
  - name: 'Bootstrap Configuration'
    description: Returns bootstrap settings and updates logging options
  - name: 'Database Configuration'
    description: Configure sync gateway databases
  - name: 'Database Management'
    description: Create and manage sync gateway databases
  - name: 'Database Security'
    description: Create and manage database users and roles
  - name: 'Access Control'
    description: Convenience API for Sync function upsert
  - name: Replication
    description: Manage inter-Sync Gateway replication
  - name: Document
    description: Manage documents and attachments
  - name: 'Design Documents'
    description: Work with sync gateway design docs
  - name: Logging
    description: Update bootstrap logging settings
  - name: Server
    description: Manage server activities
  - name: Session
    description: Manage user sessions
  # - name: user
  #   description: Create and manage sync gateway users

