Skip to content

Commit

Permalink
🎉 New Destination: Typesense (#18349)
Browse files Browse the repository at this point in the history
* Initial boilerplate

* 🎉 New Destination: Typesense

* remove .java-version

* fix doc

* add typesense to dest def

* add release stage

* add requirement to main

* auto-bump connector version

* add changelog

Co-authored-by: marcosmarxm <[email protected]>
Co-authored-by: Marcos Marx <[email protected]>
Co-authored-by: Octavia Squidington III <[email protected]>
  • Loading branch information
4 people authored Oct 28, 2022
1 parent d711781 commit c219dab
Show file tree
Hide file tree
Showing 17 changed files with 568 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -329,6 +329,12 @@
documentationUrl: https://docs.airbyte.com/integrations/destinations/tidb
icon: tidb.svg
releaseStage: alpha
- name: Typesense
destinationDefinitionId: 36be8dc6-9851-49af-b776-9d4c30e4ab6a
dockerRepository: airbyte/destination-typesense
dockerImageTag: 0.1.0
documentationUrl: https://docs.airbyte.com/integrations/destinations/typesense
releaseStage: alpha
- name: YugabyteDB
destinationDefinitionId: 2300fdcf-a532-419f-9f24-a014336e7966
dockerRepository: airbyte/destination-yugabytedb
Expand Down
45 changes: 45 additions & 0 deletions airbyte-config/init/src/main/resources/seed/destination_specs.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -6145,6 +6145,51 @@
supported_destination_sync_modes:
- "overwrite"
- "append"
- dockerImage: "airbyte/destination-typesense:0.1.0"
spec:
documentationUrl: "https://docs.airbyte.com/integrations/destinations/typesense"
connectionSpecification:
$schema: "http://json-schema.org/draft-07/schema#"
title: "Destination Typesense"
type: "object"
required:
- "api_key"
- "host"
additionalProperties: false
properties:
api_key:
title: "API Key"
type: "string"
description: "Typesense API Key"
order: 0
host:
title: "Host"
type: "string"
description: "Hostname of the Typesense instance without protocol."
order: 1
port:
title: "Port"
type: "string"
description: "Port of the Typesense instance. Ex: 8108, 80, 443. Default\
\ is 443"
order: 2
protocol:
title: "Protocol"
type: "string"
description: "Protocol of the Typesense instance. Ex: http or https. Default\
\ is https"
order: 3
batch_size:
title: "Batch size"
type: "string"
description: "How many documents should be imported together. Default 1000"
order: 4
supportsIncremental: true
supportsNormalization: false
supportsDBT: false
supported_destination_sync_modes:
- "overwrite"
- "append"
- dockerImage: "airbyte/destination-yugabytedb:0.1.0"
spec:
documentationUrl: "https://docs.airbyte.io/integrations/destinations/yugabytedb"
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
*
!Dockerfile
!main.py
!destination_typesense
!setup.py
38 changes: 38 additions & 0 deletions airbyte-integrations/connectors/destination-typesense/Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
FROM python:3.9.11-alpine3.15 as base

# build and load all requirements
FROM base as builder
WORKDIR /airbyte/integration_code

# upgrade pip to the latest version
RUN apk --no-cache upgrade \
&& pip install --upgrade pip \
&& apk --no-cache add tzdata build-base


COPY setup.py ./
# install necessary packages to a temporary folder
RUN pip install --prefix=/install .

# build a clean environment
FROM base
WORKDIR /airbyte/integration_code

# copy all loaded and built libraries to a pure basic image
COPY --from=builder /install /usr/local
# add default timezone settings
COPY --from=builder /usr/share/zoneinfo/Etc/UTC /etc/localtime
RUN echo "Etc/UTC" > /etc/timezone

# bash is installed for more convenient debugging.
RUN apk --no-cache add bash

# copy payload code only
COPY main.py ./
COPY destination_typesense ./destination_typesense

ENV AIRBYTE_ENTRYPOINT "python /airbyte/integration_code/main.py"
ENTRYPOINT ["python", "/airbyte/integration_code/main.py"]

LABEL io.airbyte.version=0.1.0
LABEL io.airbyte.name=airbyte/destination-typesense
123 changes: 123 additions & 0 deletions airbyte-integrations/connectors/destination-typesense/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
# Typesense Destination

This is the repository for the Typesense destination connector, written in Python.
For information about how to use this connector within Airbyte, see [the documentation](https://docs.airbyte.io/integrations/destinations/typesense).

## Local development

### Prerequisites
**To iterate on this connector, make sure to complete this prerequisites section.**

#### Minimum Python version required `= 3.7.0`

#### Build & Activate Virtual Environment and install dependencies
From this connector directory, create a virtual environment:
```
python -m venv .venv
```

This will generate a virtualenv for this module in `.venv/`. Make sure this venv is active in your
development environment of choice. To activate it from the terminal, run:
```
source .venv/bin/activate
pip install -r requirements.txt
```
If you are in an IDE, follow your IDE's instructions to activate the virtualenv.

Note that while we are installing dependencies from `requirements.txt`, you should only edit `setup.py` for your dependencies. `requirements.txt` is
used for editable installs (`pip install -e`) to pull in Python dependencies from the monorepo and will call `setup.py`.
If this is mumbo jumbo to you, don't worry about it, just put your deps in `setup.py` but install using `pip install -r requirements.txt` and everything
should work as you expect.

#### Building via Gradle
From the Airbyte repository root, run:
```
./gradlew :airbyte-integrations:connectors:destination-typesense:build
```

#### Create credentials
**If you are a community contributor**, follow the instructions in the [documentation](https://docs.airbyte.io/integrations/destinations/typesense)
to generate the necessary credentials. Then create a file `secrets/config.json` conforming to the `destination_typesense/spec.json` file.
Note that the `secrets` directory is gitignored by default, so there is no danger of accidentally checking in sensitive information.
See `integration_tests/sample_config.json` for a sample config file.

**If you are an Airbyte core member**, copy the credentials in Lastpass under the secret name `destination typesense test creds`
and place them into `secrets/config.json`.

### Locally running the connector
```
python main.py spec
python main.py check --config secrets/config.json
python main.py discover --config secrets/config.json
python main.py read --config secrets/config.json --catalog integration_tests/configured_catalog.json
```

### Locally running the connector docker image

#### Build
First, make sure you build the latest Docker image:
```
docker build . -t airbyte/destination-typesense:dev
```

You can also build the connector image via Gradle:
```
./gradlew :airbyte-integrations:connectors:destination-typesense:airbyteDocker
```
When building via Gradle, the docker image name and tag, respectively, are the values of the `io.airbyte.name` and `io.airbyte.version` `LABEL`s in
the Dockerfile.

#### Run
Then run any of the connector commands as follows:
```
docker run --rm airbyte/destination-typesense:dev spec
docker run --rm -v $(pwd)/secrets:/secrets airbyte/destination-typesense:dev check --config /secrets/config.json
# messages.jsonl is a file containing line-separated JSON representing AirbyteMessages
cat messages.jsonl | docker run --rm -v $(pwd)/secrets:/secrets -v $(pwd)/integration_tests:/integration_tests airbyte/destination-typesense:dev write --config /secrets/config.json --catalog /integration_tests/configured_catalog.json
```
## Testing
Make sure to familiarize yourself with [pytest test discovery](https://docs.pytest.org/en/latest/goodpractices.html#test-discovery) to know how your test files and methods should be named.
First install test dependencies into your virtual environment:
```
pip install .[tests]
```
### Unit Tests
To run unit tests locally, from the connector directory run:
```
python -m pytest unit_tests
```

### Integration Tests
There are two types of integration tests: Acceptance Tests (Airbyte's test suite for all destination connectors) and custom integration tests (which are specific to this connector).
#### Custom Integration tests
Place custom tests inside `integration_tests/` folder, then, from the connector root, run
```
python -m pytest integration_tests
```
#### Acceptance Tests
Coming soon:

### Using gradle to run tests
All commands should be run from airbyte project root.
To run unit tests:
```
./gradlew :airbyte-integrations:connectors:destination-typesense:unitTest
```
To run acceptance and custom integration tests:
```
./gradlew :airbyte-integrations:connectors:destination-typesense:integrationTest
```

## Dependency Management
All of your dependencies should go in `setup.py`, NOT `requirements.txt`. The requirements file is only used to connect internal Airbyte dependencies in the monorepo for local development.
We split dependencies between two groups, dependencies that are:
* required for your connector to work need to go to `MAIN_REQUIREMENTS` list.
* required for the testing need to go to `TEST_REQUIREMENTS` list

### Publishing a new version of the connector
You've checked out the repo, implemented a million dollar feature, and you're ready to share your changes with the world. Now what?
1. Make sure your changes are passing unit and integration tests.
1. Bump the connector version in `Dockerfile` -- just increment the value of the `LABEL io.airbyte.version` appropriately (we use [SemVer](https://semver.org/)).
1. Create a Pull Request.
1. Pat yourself on the back for being an awesome contributor.
1. Someone from Airbyte will take a look at your PR and iterate with you to merge it into master.
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
plugins {
id 'airbyte-python'
id 'airbyte-docker'
}

airbytePython {
moduleDirectory 'destination_typesense'
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
#
# Copyright (c) 2022 Airbyte, Inc., all rights reserved.
#


from .destination import DestinationTypesense

__all__ = ["DestinationTypesense"]
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
#
# Copyright (c) 2022 Airbyte, Inc., all rights reserved.
#


from logging import Logger
from typing import Any, Iterable, Mapping

from airbyte_cdk.destinations import Destination
from airbyte_cdk.models import AirbyteConnectionStatus, AirbyteMessage, ConfiguredAirbyteCatalog, DestinationSyncMode, Status, Type
from destination_typesense.writer import TypesenseWriter
from typesense import Client


def get_client(config: Mapping[str, Any]) -> Client:
api_key = config.get("api_key")
host = config.get("host")
port = config.get("port") or "8108"
protocol = config.get("protocol") or "https"

client = Client({"api_key": api_key, "nodes": [{"host": host, "port": port, "protocol": protocol}], "connection_timeout_seconds": 2})

return client


class DestinationTypesense(Destination):
def write(
self, config: Mapping[str, Any], configured_catalog: ConfiguredAirbyteCatalog, input_messages: Iterable[AirbyteMessage]
) -> Iterable[AirbyteMessage]:
client = get_client(config=config)

for configured_stream in configured_catalog.streams:
steam_name = configured_stream.stream.name
if configured_stream.destination_sync_mode == DestinationSyncMode.overwrite:
try:
client.collections[steam_name].delete()
except Exception:
pass
client.collections.create({"name": steam_name, "fields": [{"name": ".*", "type": "auto"}]})

writer = TypesenseWriter(client, steam_name, config.get("batch_size"))
for message in input_messages:
if message.type == Type.STATE:
writer.flush()
yield message
elif message.type == Type.RECORD:
writer.queue_write_operation(message.record.data)
else:
continue
writer.flush()

def check(self, logger: Logger, config: Mapping[str, Any]) -> AirbyteConnectionStatus:
try:
client = get_client(config=config)
client.collections.create({"name": "_airbyte", "fields": [{"name": "title", "type": "string"}]})
client.collections["_airbyte"].documents.create({"id": "1", "title": "The Hunger Games"})
client.collections["_airbyte"].documents["1"].retrieve()
client.collections["_airbyte"].delete()
return AirbyteConnectionStatus(status=Status.SUCCEEDED)
except Exception as e:
return AirbyteConnectionStatus(status=Status.FAILED, message=f"An exception occurred: {repr(e)}")
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
{
"documentationUrl": "https://docs.airbyte.com/integrations/destinations/typesense",
"supported_destination_sync_modes": ["overwrite", "append"],
"supportsIncremental": true,
"supportsDBT": false,
"supportsNormalization": false,
"connectionSpecification": {
"$schema": "http://json-schema.org/draft-07/schema#",
"title": "Destination Typesense",
"type": "object",
"required": ["api_key", "host"],
"additionalProperties": false,
"properties": {
"api_key": {
"title": "API Key",
"type": "string",
"description": "Typesense API Key",
"order": 0
},
"host": {
"title": "Host",
"type": "string",
"description": "Hostname of the Typesense instance without protocol.",
"order": 1
},
"port": {
"title": "Port",
"type": "string",
"description": "Port of the Typesense instance. Ex: 8108, 80, 443. Default is 443",
"order": 2
},
"protocol": {
"title": "Protocol",
"type": "string",
"description": "Protocol of the Typesense instance. Ex: http or https. Default is https",
"order": 3
},
"batch_size": {
"title": "Batch size",
"type": "string",
"description": "How many documents should be imported together. Default 1000",
"order": 4
}
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
#
# Copyright (c) 2022 Airbyte, Inc., all rights reserved.
#

from collections.abc import Mapping
from logging import getLogger
from uuid import uuid4

from typesense import Client

logger = getLogger("airbyte")


class TypesenseWriter:
write_buffer = []

def __init__(self, client: Client, steam_name: str, batch_size: int = 1000):
self.client = client
self.steam_name = steam_name
self.batch_size = batch_size

def queue_write_operation(self, data: Mapping):
random_key = str(uuid4())
data_with_id = data if "id" in data else {**data, "id": random_key}
self.write_buffer.append(data_with_id)
if len(self.write_buffer) == self.batch_size:
self.flush()

def flush(self):
buffer_size = len(self.write_buffer)
if buffer_size == 0:
return
logger.info(f"flushing {buffer_size} records")
self.client.collections[self.steam_name].documents.import_(self.write_buffer)
self.write_buffer.clear()
Loading

0 comments on commit c219dab

Please sign in to comment.