Skip to content

Incremental engine for long horizon agents 🌟 Star if you like it!

docs(connectors): Python and Rust pages for the overview, Discord, storage and stream sources (#2750)

LJ πŸ₯₯🌴d473e06ce17b
diff --git a/docs/src/content/docs/connectors/amazon_s3.mdx b/docs/src/content/docs/connectors/amazon_s3.mdx
index 2a259ab0..b20717b1 100644
--- a/docs/src/content/docs/connectors/amazon_s3.mdx
+++ b/docs/src/content/docs/connectors/amazon_s3.mdx
@@ -25,11 +25,11 @@ from cocoindex.connectors import amazon_s3
use cocoindex::connectors::amazon_s3::{self, ListOptions, S3Client, S3File};
```
-The Rust SDK needs the `amazon_s3` Cargo feature of the `cocoindex` crate. The Rust connector uses the official `aws-sdk-s3` crate, re-exported as `cocoindex::connectors::amazon_s3::aws_sdk_s3`.
-
</Fragment>
</LangTabs>
+<Lang only="python">
+
:::note[Installation]
This connector requires the `aiobotocore` library. Install with:
@@ -38,16 +38,46 @@ pip install cocoindex[amazon_s3]
```
:::
+</Lang>
+
+<Lang only="rust">
+
+:::note[Installation]
+Enable the `amazon_s3` feature of the `cocoindex` crate:
+
+```toml
+cocoindex = { git = "https://github.com/cocoindex-io/cocoindex", features = ["amazon_s3"] }
+```
+
+The connector uses the official `aws-sdk-s3` crate, re-exported as `cocoindex::connectors::amazon_s3::aws_sdk_s3`, so you can create buckets and upload objects without a direct dependency.
+:::
+
+</Lang>
+
## As source
The connector provides two ways to read from S3:
+<Lang only="python">
+
- `list_objects()` β€” List and iterate over objects in a bucket (with optional prefix and filtering)
- `get_object()` β€” Fetch a single object by its key
- `read()` β€” Read object content directly by S3 URI
Both require an aiobotocore S3 client, which you create and manage yourself:
+</Lang>
+
+<Lang only="rust">
+
+- `list_objects()` β€” List the objects in a bucket (with optional prefix and filtering)
+- `S3Client::get_object()` / `S3Client::get_object_uri()` β€” Fetch a single object by its key or `s3://` URI
+- `S3Client::read()` β€” Read an object's content
+
+All of them go through an `S3Client`, which you create and provide to the app as a context key:
+
+</Lang>
+
{/* Rust: examples/rust/amazon_s3_embedding/src/main.rs; rust/sdk/cocoindex/src/connectors/amazon_s3.rs (S3Client) */}
<LangTabs>
<Fragment slot="python">
@@ -97,7 +127,7 @@ let app = Environment::builder()
### list_objects
-List objects in an S3 bucket. Returns an `S3Walker` that supports async iteration.
+List objects in an S3 bucket. Returns an `S3Walker`<Lang only="python"> that supports async iteration</Lang>.
{/* Rust: rust/sdk/cocoindex/src/connectors/amazon_s3.rs */}
<LangTabs>
@@ -137,11 +167,13 @@ pub async fn S3Walker::list(&self) -> Result<Vec<S3File>>
pub async fn S3Walker::items(&self) -> Result<Vec<(String, S3File)>>
```
-The walker is not an iterator: `list()` returns every matching object, and `items()` the `(key, file)` pairs for `mount_each!`. The Rust prefix is passed to S3 as given, so `"data"` also matches `database.csv`: name a folder with its trailing slash, `"data/"`. The prefix and a `/` after it are stripped from the relative keys.
+The walker is not an iterator: `list()` returns every matching object, and `items()` the `(key, file)` pairs for `mount_each!`.
</Fragment>
</LangTabs>
+<Lang only="python">
+
**Parameters:**
- `client` β€” An aiobotocore S3 client.
@@ -152,9 +184,29 @@ The walker is not an iterator: `list()` returns every matching object, and `item
**Returns:** An `S3Walker` that can be used with `async for` loops.
+</Lang>
+
+<Lang only="rust">
+
+**Parameters:**
+
+- `client` β€” The `S3Client`.
+- `bucket` β€” The S3 bucket name.
+- `options.prefix` β€” Only list objects whose key starts with this prefix. The prefix and a `/` after it are stripped from the relative keys of the returned files.
+- `options.path_matcher` β€” Optional filter for files. Patterns are matched against the relative path (after prefix stripping). See [PatternFilePathMatcher](../common_resources/data_types#patternfilepathmatcher).
+- `options.max_file_size` β€” Skip objects larger than this size in bytes.
+
+**Returns:** An `S3Walker`; `list()` and `items()` list the bucket once each time you call them.
+
+</Lang>
+
+<RustNote>
+The prefix is passed to S3 as given, not read as a folder: `"data"` also matches `database.csv`. Name a folder with its trailing slash, `"data/"`, and select objects by the start of their name with `path_matcher`.
+</RustNote>
+
### Iterating files
-`list_objects()` returns an `S3Walker` that yields `S3File` objects (implementing the [`FileLike`](../common_resources/data_types#filelike) base class):
+`list_objects()` returns an `S3Walker` that <Lang only="python">yields</Lang><Lang only="rust">lists</Lang> `S3File` objects (implementing the [`FileLike`](../common_resources/data_types#filelike) base class):
{/* Rust: rust/sdk/cocoindex/tests/amazon_s3_source.rs */}
<LangTabs>
@@ -200,7 +252,7 @@ See [`FileLike`](../common_resources/data_types#filelike) for details on the fil
### Keyed iteration with `items()`
-`S3Walker.items()` yields `(str, S3File)` pairs, useful for associating each file with a stable string key: the object key relative to the prefix, exactly as stored. Keys are not normalized, so `a//b.txt` and `a/b.txt` are two items:
+<Lang only="python">`S3Walker.items()` yields `(str, S3File)` pairs</Lang><Lang only="rust">`S3Walker::items()` returns `(String, S3File)` pairs</Lang>, useful for associating each file with a stable string key: the object key relative to the prefix, exactly as stored. Keys are not normalized, so `a//b.txt` and `a/b.txt` are two items:
{/* Rust: rust/sdk/cocoindex/tests/amazon_s3_source.rs */}
<LangTabs>
@@ -256,14 +308,11 @@ let files = amazon_s3::list_objects(
&bucket,
ListOptions {
prefix,
- path_matcher: Some(Arc::new(
- PatternFilePathMatcher::include(["**/*.md"])
- .map_err(|e| Error::engine(format!("matcher: {e}")))?,
- )),
+ path_matcher: Some(Arc::new(PatternFilePathMatcher::include(["**/*.md"])?)),
..Default::default()
},
)
-.list()
+.items()
.await?;
```
@@ -330,18 +379,29 @@ pub async fn S3Client::get_object(&self, bucket: &str, key: &str) -> Result<S3Fi
pub async fn S3Client::get_object_uri(&self, uri: &str) -> Result<S3File>
```
-The two Python forms are two Rust methods on the client.
-
</Fragment>
</LangTabs>
+<Lang only="python">
+
**Parameters:**
- `client` β€” An aiobotocore S3 client.
- `bucket_name_or_uri` β€” Either a full S3 URI (`s3://bucket/key`) or the bucket name when `key` is supplied separately.
- `key` β€” The full S3 object key. Required when `bucket_name_or_uri` is a bucket name; must be omitted when a URI is given.
-**Returns:** An `S3File` (FileLike) for the specified object.
+</Lang>
+
+<Lang only="rust">
+
+**Parameters:**
+
+- `bucket`, `key` β€” The bucket name and the full S3 object key, for `get_object`.
+- `uri` β€” A full S3 URI (`s3://bucket/key`), for `get_object_uri`.
+
+</Lang>
+
+**Returns:** An `S3File` (FileLike) for the specified object. Its relative path is the full key. It is an error if the object does not exist.
**Example:**
@@ -382,7 +442,7 @@ let data = f.read().await?;
### read
-Read object content directly from an S3 URI, without fetching metadata first.
+<Lang only="python">Read object content directly from an S3 URI, without fetching metadata first.</Lang><Lang only="rust">Read an object's content through the client.</Lang>
{/* Rust: rust/sdk/cocoindex/src/connectors/amazon_s3.rs */}
<LangTabs>
@@ -405,11 +465,17 @@ pub async fn S3Client::read_range(&self, file: &S3File, len: u64) -> Result<Vec<
pub async fn S3Client::read_text(&self, file: &S3File) -> Result<String>
```
-The Rust client reads an `S3File`, not a URI: get the file with `get_object_uri` first. `read_range` reads the first `len` bytes.
+`read_range` reads the first `len` bytes with a ranged request. `read_text` decodes the content as UTF-8 (BOM-aware, lossy on invalid UTF-8).
</Fragment>
</LangTabs>
+<RustNote>
+The client reads an `S3File`, not a URI: get the file with `get_object_uri` first, which costs one metadata request.
+</RustNote>
+
+<Lang only="python">
+
**Parameters:**
- `client` β€” An aiobotocore S3 client.
@@ -418,6 +484,8 @@ The Rust client reads an `S3File`, not a URI: get the file with `get_object_uri`
**Returns:** The object content as bytes.
+</Lang>
+
**Example:**
{/* Rust: rust/sdk/cocoindex/tests/amazon_s3_source.rs */}
@@ -445,6 +513,8 @@ let head = client.read_range(&f, 3).await?;
Each file returned by the connector has an `S3FilePath` β€” a [`FilePath`](../common_resources/data_types#filepath) specialized for S3:
+<Lang only="python">
+
- **Relative path** (`file.file_path.path`) β€” The object key relative to the walker prefix (or the full key if no prefix was used).
- **Resolved path** (`file.file_path.resolve()`) β€” The full S3 object key.
- **Identity** β€” Two `S3FilePath`s are equal only if they have the same bucket and the same relative key.
@@ -455,7 +525,26 @@ For example, with `prefix="data/"` and an object key `"data/docs/readme.md"`:
A derived path (`parent`, `/`, `with_name()`, `with_suffix()`) resolves to the object key of the new path in the same folder: `file.file_path.with_suffix(".txt").resolve()` β†’ `"data/docs/readme.txt"`.
-The Rust `S3FilePath` (`file.file_path()`) has `bucket()`, `path()` (the relative key, a `&str`) and `resolve()` (the full object key). Its memo key is the bucket and the relative key. It has no derived-path methods. `S3File` has the public fields `size`, `modified_secs` and `etag`, plus `key()`, `read()`, `read_size(n)` and `read_text()`; it implements `FileLike` and `MemoInput`.
+</Lang>
+
+<Lang only="rust">
+
+- **Relative path** (`file.file_path().path()`, a `&str`) β€” The object key relative to the walker prefix (or the full key if no prefix was used). `file.key()` returns it as a `String`, the key for `mount_each!`.
+- **Resolved path** (`file.file_path().resolve()`) β€” The full S3 object key.
+- **Bucket** (`file.file_path().bucket()`).
+- **Identity** β€” The memo key is the bucket and the relative key.
+
+For example, with `prefix: "data/"` and an object key `"data/docs/readme.md"`:
+- `file.file_path().path()` β†’ `"docs/readme.md"`
+- `file.file_path().resolve()` β†’ `"data/docs/readme.md"`
+
+`S3File` has the public fields `size`, `modified_secs` and `etag`, plus `key()`, `read()`, `read_size(n)` and `read_text()`; it implements `FileLike` and `MemoInput`. Its memo key holds only stable metadata (the path, size, modified time and ETag), never the client.
+
+</Lang>
+
+<RustNote>
+`S3FilePath` has no derived-path methods (`parent`, `/`, `with_name()`, `with_suffix()`).
+</RustNote>
### Example
@@ -506,8 +595,8 @@ use cocoindex::resources::file::PatternFilePathMatcher;
cocoindex::context_key!(static S3: S3Client);
#[cocoindex::function(memo)]
-async fn process_file(ctx: &Ctx, file: S3File) -> Result<()> {
- let text = ctx.get_key(&S3)?.read_text(&file).await?;
+async fn process_file(_ctx: &Ctx, file: S3File) -> Result<()> {
+ let text = file.read_text().await?;
// ... process the file content ...
Ok(())
}
@@ -518,21 +607,14 @@ async fn app_main(ctx: Ctx, bucket: String, prefix: String) -> Result<()> {
&bucket,
ListOptions {
prefix,
- path_matcher: Some(Arc::new(
- PatternFilePathMatcher::include(["**/*.md"])
- .map_err(|e| Error::engine(format!("matcher: {e}")))?,
- )),
+ path_matcher: Some(Arc::new(PatternFilePathMatcher::include(["**/*.md"])?)),
..Default::default()
},
)
- .list()
+ .items()
.await?;
- mount_each!(
- files.into_iter().map(|f| (f.key(), f)),
- |file| process_file(ctx, file)
- )
- .await?;
+ mount_each!(files, |file| process_file(ctx, file)).await?;
Ok(())
}
```
diff --git a/docs/src/content/docs/connectors/azure_blob.mdx b/docs/src/content/docs/connectors/azure_blob.mdx
index 647a4b35..dd74d2b6 100644
--- a/docs/src/content/docs/connectors/azure_blob.mdx
+++ b/docs/src/content/docs/connectors/azure_blob.mdx
@@ -26,11 +26,11 @@ use cocoindex::connectors::azure_blob::{
};
```
-The Rust SDK needs the `azure_blob` Cargo feature of the `cocoindex` crate. The Rust connector speaks the Blob service REST API directly; it does not use the Azure SDK.
-
</Fragment>
</LangTabs>
+<Lang only="python">
+
:::note[Installation]
This connector uses the Azure async SDK. Install with:
@@ -39,6 +39,22 @@ pip install cocoindex[azure_blob]
```
:::
+</Lang>
+
+<Lang only="rust">
+
+:::note[Installation]
+Enable the `azure_blob` feature of the `cocoindex` crate:
+
+```toml
+cocoindex = { git = "https://github.com/cocoindex-io/cocoindex", features = ["azure_blob"] }
+```
+
+The connector speaks the Blob service REST API directly; it does not depend on an Azure SDK crate.
+:::
+
+</Lang>
+
## As source
The connector provides three read helpers:
@@ -47,11 +63,21 @@ The connector provides three read helpers:
- `get_blob()` fetches a single blob by name.
- `read()` reads blob content directly by name.
-All helpers take an async Azure `ContainerClient`. Create and close the client in your app lifespan. The Rust helpers take the SDK's own `azure_blob::ContainerClient`, built with `ContainerClient::new(account_url, container_name, credential)`.
+<Lang only="python">
+
+All helpers take an async Azure `ContainerClient`. Create and close the client in your app lifespan.
+
+</Lang>
+
+<Lang only="rust">
+
+All helpers take the connector's own `azure_blob::ContainerClient`, a handle to one container built with `ContainerClient::new(account_url, container_name, credential)`.
+
+</Lang>
### Connection setup
-Use Azure's SDK authentication methods directly. For local development, `DefaultAzureCredential` can use your Azure CLI login:
+<Lang only="python">Use Azure's SDK authentication methods directly. For local development, `DefaultAzureCredential` can use your Azure CLI login:</Lang><Lang only="rust">The `credential` is a `Credential`: an Entra ID token the client gets and renews itself, a SAS token, a storage account access key, or a bearer token you obtained. For local development, `TokenCredential::Default` can use your Azure CLI login:</Lang>
```bash
az login
@@ -92,7 +118,7 @@ let client = ContainerClient::new(
)?;
```
-`TokenCredential::Default` is the Rust form of `DefaultAzureCredential`: it takes the first source that is configured where the process runs, a service principal from `AZURE_TENANT_ID`, `AZURE_CLIENT_ID` and `AZURE_CLIENT_SECRET`, the managed identity of the Azure resource the process runs on, or the account signed in with `az login`. `TokenCredential::ClientSecret`, `TokenCredential::ManagedIdentity` and `TokenCredential::AzureCli` name one source. The client renews the token as it expires. `Credential::BearerToken` takes an access token for the `https://storage.azure.com/` resource that you obtained yourself, such as the one `az account get-access-token --resource https://storage.azure.com/` prints, and does not renew it.
+`TokenCredential::Default` takes the sources of the Azure SDK's `DefaultAzureCredential` that need no interactive sign-in. It uses the first source that is configured where the process runs, a service principal from `AZURE_TENANT_ID`, `AZURE_CLIENT_ID` and `AZURE_CLIENT_SECRET`, the managed identity of the Azure resource the process runs on, or the account signed in with `az login`. `TokenCredential::ClientSecret { tenant_id, client_id, client_secret }`, `TokenCredential::ManagedIdentity { client_id }` (`None` for the system-assigned identity) and `TokenCredential::AzureCli` name one source. The client gets the token on the first request and renews it shortly before it expires. `Credential::BearerToken` takes an access token for the `https://storage.azure.com/` resource that you obtained yourself, such as the one `az account get-access-token --resource https://storage.azure.com/` prints, and does not renew it.
</Fragment>
</LangTabs>
@@ -158,7 +184,7 @@ let client = ContainerClient::new(
)?;
```
-A `ContainerClient` is `Clone` and has no `close()`; provide it under a `ContextKey` with `Environment::builder().provide_key(&CONTAINER, client)`. An account URL with a path, such as the Azurite emulator's `http://127.0.0.1:10000/devstoreaccount1`, names the account by the first path segment.
+A `ContainerClient` is `Clone` and has no `close()`; declare a key with `cocoindex::context_key!(static CONTAINER: ContainerClient)` and provide the client with `Environment::builder().provide_key(&CONTAINER, client)`. An account URL with a path, such as the Azurite emulator's `http://127.0.0.1:10000/devstoreaccount1`, names the account by the first path segment.
</Fragment>
</LangTabs>
@@ -167,7 +193,7 @@ The identity must have permission to list and read blobs. With Azure role-based
### list_blobs
-List blobs in an Azure Blob Storage container. Returns an `AzureBlobWalker` that supports async iteration.
+List blobs in an Azure Blob Storage container. Returns an `AzureBlobWalker`<Lang only="python"> that supports async iteration</Lang>.
{/* Rust: rust/sdk/cocoindex/src/connectors/azure_blob.rs */}
<LangTabs>
@@ -209,16 +235,16 @@ pub async fn AzureBlobWalker::items(&self) -> Result<Vec<(String, AzureBlobFile)
**Parameters:**
-- `container_client` - An async Azure `ContainerClient`.
+- `container_client` - <Lang only="python">An async Azure `ContainerClient`.</Lang><Lang only="rust">The `ContainerClient` (the argument is named `client`).</Lang>
- `prefix` - Only list blobs in this folder. A prefix names a folder: `"docs"` and `"docs/"` both list the blobs under `docs/`, and neither lists `docsa.md`. The folder is stripped from relative paths in returned files. To select blobs by the start of their name (for example `2024-*.csv`), use `path_matcher`.
- `path_matcher` - Optional filter for files. Patterns are matched against the relative path after prefix stripping. See [PatternFilePathMatcher](../common_resources/data_types#patternfilepathmatcher).
- `max_file_size` - Skip blobs larger than this size in bytes.
-**Returns:** An `AzureBlobWalker` that can be used with `async for` loops.
+**Returns:** An `AzureBlobWalker` <Lang only="python">that can be used with `async for` loops.</Lang><Lang only="rust">whose `list()` and `items()` list the container once each time you call them.</Lang>
### Iterating files
-`list_blobs()` yields `AzureBlobFile` objects implementing [`FileLike`](../common_resources/data_types#filelike):
+`list_blobs()` <Lang only="python">yields</Lang><Lang only="rust">lists</Lang> `AzureBlobFile` objects implementing [`FileLike`](../common_resources/data_types#filelike):
{/* Rust: rust/sdk/cocoindex/tests/azure_blob_source.rs */}
<LangTabs>
@@ -256,7 +282,7 @@ for file in files {
### Keyed iteration with `items()`
-`AzureBlobWalker.items()` yields `(str, AzureBlobFile)` pairs. The key is the blob name relative to the prefix, exactly as stored. Keys are not normalized, so `a//b.txt` and `a/b.txt` are two items:
+<Lang only="python">`AzureBlobWalker.items()` yields `(str, AzureBlobFile)` pairs.</Lang><Lang only="rust">`AzureBlobWalker::items()` returns `(String, AzureBlobFile)` pairs.</Lang> The key is the blob name relative to the prefix, exactly as stored. Keys are not normalized, so `a//b.txt` and `a/b.txt` are two items:
{/* Rust: rust/sdk/SHOWCASE.md (Azure Blob), verified against rust/sdk/cocoindex/src/connectors/azure_blob.rs */}
<LangTabs>
@@ -387,7 +413,7 @@ pub async fn get_blob(client: &ContainerClient, blob_name: &str) -> Result<Azure
**Parameters:**
-- `container_client` - An async Azure `ContainerClient`.
+- `container_client` - <Lang only="python">An async Azure `ContainerClient`.</Lang><Lang only="rust">The `ContainerClient` (the argument is named `client`).</Lang>
- `blob_name` - The full blob name in the container.
**Returns:** An `AzureBlobFile` for the specified blob.
@@ -443,16 +469,14 @@ pub async fn read(
) -> Result<Vec<u8>>
```
-`size` is `None` for the whole blob, or `Some(n)` for its first `n` bytes.
-
</Fragment>
</LangTabs>
**Parameters:**
-- `container_client` - An async Azure `ContainerClient`.
+- `container_client` - <Lang only="python">An async Azure `ContainerClient`.</Lang><Lang only="rust">The `ContainerClient` (the argument is named `client`).</Lang>
- `blob_name` - The full blob name in the container.
-- `size` - Number of bytes to read. If `-1`, read the entire blob.
+- `size` - Number of bytes to read. <Lang only="python">If `-1`, read the entire blob.</Lang><Lang only="rust">`None` reads the entire blob.</Lang>
**Returns:** The blob content as bytes.
@@ -480,6 +504,8 @@ let data = azure_blob::read(client, "docs/readme.md", None).await?;
Each file returned by the connector has an `AzureBlobFilePath`, a [`FilePath`](../common_resources/data_types#filepath) specialized for Azure Blob Storage:
+<Lang only="python">
+
- **Relative path** (`file.file_path.path`) - The blob name relative to the walker prefix, or the full blob name if no prefix was used.
- **Resolved path** (`file.file_path.resolve()`) - The full blob name in the container.
- **Identity** - Two `AzureBlobFilePath`s are equal only if they have the same account, container and relative name.
@@ -491,7 +517,27 @@ For example, with `prefix="docs/"` and blob name `"docs/readme.md"`:
A derived path (`parent`, `/`, `with_name()`, `with_suffix()`) resolves to the blob name of the new path in the same folder: `file.file_path.with_suffix(".txt").resolve()` returns `"docs/readme.txt"`.
-The Rust `AzureBlobFilePath` (`file.file_path()`) has `account_name()`, `container_name()`, `path()` (the relative name, a `&str`), `blob_name()` and `resolve()` (the full blob name). Its memo key is `(account_name, container_name, relative_path)`. It has no derived-path methods. `AzureBlobFile` has the public fields `size`, `modified_secs` and `etag`, plus `key()`, `read()`, `read_size(n)` and `read_text()`; it implements `FileLike` and `MemoInput`.
+</Lang>
+
+<Lang only="rust">
+
+- **Relative path** (`file.file_path().path()`, a `&str`) - The blob name relative to the walker prefix, or the full blob name if no prefix was used. `file.key()` returns it as a `String`, the key for `mount_each!`.
+- **Resolved path** (`file.file_path().resolve()`, also `blob_name()`) - The full blob name in the container.
+- **Account and container** (`account_name()`, `container_name()`).
+- **Identity** - The memo key is `(account_name, container_name, relative_path)`.
+
+For example, with `prefix: "docs/"` and blob name `"docs/readme.md"`:
+
+- `file.file_path().path()` returns `"readme.md"`
+- `file.file_path().resolve()` returns `"docs/readme.md"`
+
+`AzureBlobFile` has the public fields `size`, `modified_secs` and `etag`, plus `key()`, `read()`, `read_size(n)` and `read_text()`; it implements `FileLike` and `MemoInput`. Its memo key holds only stable metadata, never the client.
+
+</Lang>
+
+<RustNote>
+`AzureBlobFilePath` has no derived-path methods (`parent`, `/`, `with_name()`, `with_suffix()`).
+</RustNote>
### Example
@@ -533,7 +579,7 @@ use cocoindex::resources::file::PatternFilePathMatcher;
cocoindex::context_key!(static CONTAINER: ContainerClient);
#[cocoindex::function(memo)]
-async fn process_file(ctx: &Ctx, file: AzureBlobFile) -> Result<()> {
+async fn process_file(_ctx: &Ctx, file: AzureBlobFile) -> Result<()> {
let text = file.read_text().await?;
// Process the file content.
Ok(())
@@ -567,4 +613,4 @@ async fn app_main(ctx: Ctx, prefix: String) -> Result<()> {
</Fragment>
</LangTabs>
-See `examples/azure_blob_embedding` for a runnable project, and `examples/rust/azure_blob_embedding` for the Rust one.
+See <Lang only="python">`examples/azure_blob_embedding`</Lang><Lang only="rust">`examples/rust/azure_blob_embedding`</Lang> for a runnable project.
diff --git a/docs/src/content/docs/connectors/discord.mdx b/docs/src/content/docs/connectors/discord.mdx
index cbec3fdd..c3815639 100644
--- a/docs/src/content/docs/connectors/discord.mdx
+++ b/docs/src/content/docs/connectors/discord.mdx
@@ -1,6 +1,8 @@
---
title: "*Discord* connector"
toc_max_heading_level: 4
+languages: [python]
+rust_counterpart: connectors
description: >
Index the messages and threads of Discord text, announcement and forum
channels with your own bot's token. Each run lists every channel, and only
diff --git a/docs/src/content/docs/connectors/google_drive.mdx b/docs/src/content/docs/connectors/google_drive.mdx
index b1bcd560..f109e8f0 100644
--- a/docs/src/content/docs/connectors/google_drive.mdx
+++ b/docs/src/content/docs/connectors/google_drive.mdx
@@ -25,11 +25,11 @@ from cocoindex.connectors import google_drive
use cocoindex::connectors::gdrive::{DriveFile, GoogleDriveClient, GoogleDriveSource};
```
-The Rust module is `gdrive`, and the Rust SDK needs the `google_drive` Cargo feature of the `cocoindex` crate.
-
</Fragment>
</LangTabs>
+<Lang only="python">
+
:::note[Dependencies]
This connector requires additional dependencies. Install with:
@@ -39,10 +39,27 @@ pip install cocoindex[google_drive]
:::
+</Lang>
+
+<Lang only="rust">
+
+:::note[Dependencies]
+The module is `cocoindex::connectors::gdrive`, behind the `google_drive` feature of the `cocoindex` crate:
+
+```toml
+cocoindex = { git = "https://github.com/cocoindex-io/cocoindex", features = ["google_drive"] }
+```
+
+:::
+
+</Lang>
+
## As source
The connector provides two ways to read from Google Drive:
+<Lang only="python">
+
- `GoogleDriveSource` β€” high-level source class with async iteration
- `list_files()` β€” lower-level function returning a sync iterator
@@ -51,7 +68,21 @@ Both authenticate with one of:
- a **service account** with access to the target Drive folders (`service_account_credential_path`), the fit for a shared or automated setup;
- a **personal Google account** signed in once through OAuth (`user_account`, experimental), the fit for your own Drive: see [Signing in with a personal account](#signing-in-with-a-personal-account).
-In Rust the authentication lives in a `GoogleDriveClient`: `GoogleDriveClient::from_service_account_file(path)?` for a service account, `GoogleDriveClient::from_user_account(&account)?` for a personal account. The client is `Clone` and is provided under a `ContextKey` so that functions can read files through it.
+</Lang>
+
+<Lang only="rust">
+
+- `GoogleDriveSource` β€” the source, with `list_files()` and `items()`
+- `list_files()` β€” a function over a `GoogleDriveSourceSpec`
+
+Both read through a `GoogleDriveClient`, which authenticates with one of:
+
+- a **service account** with access to the target Drive folders (`GoogleDriveClient::from_service_account_file(path)?`), the fit for a shared or automated setup;
+- a **personal Google account** signed in once through OAuth (`GoogleDriveClient::from_user_account(&account)?`, experimental), the fit for your own Drive: see [Signing in with a personal account](#signing-in-with-a-personal-account).
+
+The client is `Clone`; provide it under a context key so that functions can read files through it.
+
+</Lang>
### Setting up a service account
@@ -68,7 +99,7 @@ gws auth login
gws drive files list
```
-In headless or agent workflows, `gws` can also read credentials from `GOOGLE_WORKSPACE_CLI_CREDENTIALS_FILE`. CocoIndex still expects the service account JSON path in `service_account_credential_path`; use the `gws` credentials setting for `gws` commands themselves.
+In headless or agent workflows, `gws` can also read credentials from `GOOGLE_WORKSPACE_CLI_CREDENTIALS_FILE`. CocoIndex still expects the service account JSON path in <Lang only="python">`service_account_credential_path`</Lang><Lang only="rust">`GoogleDriveClient::from_service_account_file`</Lang>; use the `gws` credentials setting for `gws` commands themselves.
:::
### GoogleDriveSource
@@ -110,14 +141,26 @@ let source = GoogleDriveSource::new(ctx.get_key(&GDRIVE)?.clone(), root_folder_i
**Parameters:**
+<Lang only="python">
+
- `root_folder_ids` β€” List of Google Drive folder IDs to scan. Subfolders are traversed recursively.
- `service_account_credential_path` β€” Path to the service account JSON credential file.
- `user_account` β€” A [`UserAccount`](#useraccount) signed in through OAuth (experimental). Exactly one of `service_account_credential_path` and `user_account` is given.
- `mime_types` β€” Optional list of MIME types to include. If `None`, all file types are included.
+</Lang>
+
+<Lang only="rust">
+
+- `client` β€” The `GoogleDriveClient`, signed in with a service account or a [`UserAccount`](#useraccount).
+- `root_folder_ids` β€” Google Drive folder IDs to scan. Subfolders are traversed recursively.
+- `mime_types` β€” Optional MIME types to include, set with `.mime_types(...)`. Without it, all file types are included.
+
+</Lang>
+
### Iterating files
-`GoogleDriveSource` provides async iteration via `files()`, yielding `DriveFile` objects (implementing the [`FileLike`](../common_resources/data_types#filelike) base class):
+<Lang only="python">`GoogleDriveSource` provides async iteration via `files()`, yielding `DriveFile` objects</Lang><Lang only="rust">`GoogleDriveSource::list_files()` lists `DriveFile` objects</Lang> (implementing the [`FileLike`](../common_resources/data_types#filelike) base class):
{/* Rust: examples/rust/gdrive_text_embedding/src/main.rs */}
<LangTabs>
@@ -154,7 +197,7 @@ for file in source.list_files().await? {
### Keyed iteration with `items()`
-`items()` yields `(str, DriveFile)` pairs keyed by the file's Google Drive ID. IDs remain stable across renames and avoid collisions when files share a name, including within the same folder. This is useful with `mount_each()`:
+`items()` <Lang only="python">yields `(str, DriveFile)` pairs</Lang><Lang only="rust">returns `(String, DriveFile)` pairs</Lang> keyed by the file's Google Drive ID. IDs remain stable across renames and avoid collisions when files share a name, including within the same folder. This is useful with <Lang only="python">`mount_each()`</Lang><Lang only="rust">`mount_each!`</Lang>:
{/* Rust: examples/rust/gdrive_text_embedding/src/main.rs */}
<LangTabs>
@@ -169,14 +212,11 @@ async for key, file in source.items():
<Fragment slot="rust">
```rust
-let files = source.list_files().await?;
-let rows_by_file = use_mount_each!(files.into_iter().map(|file| (file.key(), file)), |file| {
- process_file(ctx, file)
-})
-.await?;
+let files = source.items().await?;
+mount_each!(files, |file| process_file(ctx, file, table)).await?;
```
-`file.key()` is the file's Google Drive ID; `source.items().await?` returns the same `(key, file)` pairs as a `Vec`.
+`file.key()` is the same Google Drive ID.
</Fragment>
</LangTabs>
@@ -246,21 +286,32 @@ pub async fn list_files(spec: GoogleDriveSourceSpec) -> Result<Vec<DriveFile>>
**Parameters:**
-- `spec` β€” A `GoogleDriveSourceSpec` with the same fields as `GoogleDriveSource` constructor parameters. In Rust the spec holds the `GoogleDriveClient` instead of a credential path.
+- `spec` β€” A `GoogleDriveSourceSpec` with the same fields as <Lang only="python">`GoogleDriveSource` constructor parameters</Lang><Lang only="rust">`GoogleDriveSource`: the client, the root folder IDs and the optional MIME types</Lang>.
-**Returns:** A sync iterator of `DriveFile` objects. The Rust function is `async` and returns a `Vec<DriveFile>`.
+**Returns:** <Lang only="python">A sync iterator of `DriveFile` objects.</Lang><Lang only="rust">Every listed `DriveFile`, as a `Vec`.</Lang>
### DriveFile
`DriveFile` implements [`FileLike`](../common_resources/data_types#filelike) with Google Drive-specific behavior:
-- `info` β€” The `DriveFileInfo` the listing returned: file ID, name, MIME type, size, modified time and MD5 checksum (binary files only).
+<Lang only="python">
+
- `info` β€” The `DriveFileInfo` the listing returned: file ID, name, MIME type, size, modified time and MD5 checksum (binary files only).
- `file_path` β€” A `DriveFilePath` containing the path relative to the configured root folder; `resolve()` returns the Google Drive file ID. If roots overlap or a file is reachable more than once, it is emitted once using the first path encountered in breadth-first traversal. Each folder's children are visited in order of name, then ID, so the same path is kept on every run.
-- `read()` / `read_text()` β€” Downloads file content via the Google Drive API. Partial reads (`size` parameter) are not supported. Requests Google refuses for rate limits (HTTP 429, or 403 with a rate-limit reason) are retried with backoff.
-- Change detection uses the Drive MD5 checksum of binary files, so an unchanged file is not downloaded again. Google Docs, Sheets and Slides have no checksum; their exported content is hashed instead.
+- `read()` / `read_text()` β€” Downloads file content via the Google Drive API. Partial reads (`size` parameter) are not supported.
+
+</Lang>
+
+<Lang only="rust">
-The Rust `DriveFile` has the public fields `file_id`, `name`, `path`, `mime_type`, `size`, `modified_time` and `md5_checksum`, plus `info()`, `key()`, `file_path()` (a `DriveFilePath` with `path()`, `file_id()` and `resolve()`), `read()` and `read_text()`. It implements `FileLike` and `MemoInput`, with the same change detection: a memoized function takes it as an argument and runs again only for a file whose content changed.
+- Public fields `file_id`, `name`, `path`, `mime_type`, `size`, `modified_time` (RFC 3339, as Drive returns it) and `md5_checksum` (binary files only); `info()` returns them as a `DriveFileInfo`, and `key()` returns the file ID.
+- `file_path()` β€” A `DriveFilePath` with `path()`, the path relative to the configured root folder, and `file_id()`; `resolve()` returns the Google Drive file ID. If roots overlap or a file is reachable more than once, it is emitted once using the first path encountered in breadth-first traversal. Each folder's children are visited in order of name, then ID, so the same path is kept on every run.
+- `read()` / `read_text()` β€” Downloads file content via the Google Drive API. A listed file carries the client; `client.read(&file)` and `client.read_text(&file)` read through a client you hold.
+
+</Lang>
+
+- Every Drive API request, listing and download alike, is retried with backoff (up to five more attempts) when Google answers with a server error, HTTP 429, or 403 with a rate-limit reason, or when the connection fails.
+- Change detection uses the Drive MD5 checksum of binary files, so an unchanged file is not downloaded again. Google Docs, Sheets and Slides have no checksum; their exported content is hashed instead.<Lang only="rust"> `DriveFile` implements `MemoInput`: a memoized function that takes it runs again only for a file whose content changed. Its memo key holds only the file's metadata, never the client.</Lang>
## Signing in with a personal account
@@ -272,6 +323,12 @@ A service account only sees folders shared with it. To read your own Drive, sign
CocoIndex's own OAuth client is not in a release yet: Google has to verify it first. Until a release includes it, sign in with an OAuth client you create in your own Google Cloud project, as below. A release that includes it needs nothing but your Google account: `cocoindex google-drive sign-in` without a client file.
+<Lang only="rust">
+
+The built-in client is compiled in only when `COCOINDEX_GOOGLE_OAUTH_CLIENT_ID` and `COCOINDEX_GOOGLE_OAUTH_CLIENT_SECRET` are set at build time, as a release build sets them. A `cocoindex` crate or `cocoindex` CLI built from the git repository has none, so its sign-in takes your own client file.
+
+</Lang>
+
### Setting up the OAuth client
Once per Google Cloud project:
@@ -304,9 +361,17 @@ The tokens are stored in a file readable by your user only (`0600`), at `~/.conf
cocoindex google-drive sign-out # revokes the sign-in at Google and deletes the token file
```
+<Lang only="python">
+
The same two steps are available in Python as `UserAccount().sign_in(client_secrets_path)` (with no argument for CocoIndex's own client) and `UserAccount().sign_out()`.
-The `cocoindex` binary for Rust projects has the same two commands. The Rust `UserAccount` reads and writes the same token file as the Python SDK, at the same default location, so one sign-in serves both. From code, `UserAccount::new()?.sign_in(Some(client_secrets_path)).await?` signs in with your own client and `sign_in(None)` with the client built into the release, when it has one; `sign_out().await?` revokes the sign-in and deletes the file.
+</Lang>
+
+<Lang only="rust">
+
+These are commands of the [`cocoindex` CLI for Rust projects](/docs/rust/cli/#google-drive). The Python CLI has the same two commands over the same token file, at the same default location, so one sign-in serves both SDKs. From code, `UserAccount::new()?.sign_in(Some(client_secrets_path)).await?` signs in with your own client and `sign_in(None)` with the client built into the release, when it has one; `sign_out().await?` revokes the sign-in and deletes the file.
+
+</Lang>
### UserAccount
@@ -336,12 +401,26 @@ pub fn UserAccount::is_signed_in(&self) -> bool
</Fragment>
</LangTabs>
+<Lang only="python">
+
The handle a run passes to `GoogleDriveSource`. It reads the token file at `token_path` (default: the path `sign-in` writes to) when the source is first used:
- the access token is refreshed with the stored refresh token as it expires, and the refreshed token is written back to the file;
- `email` is the signed-in account's address, and the memo key of a `UserAccount` is that address: a refreshed token does not invalidate memoized work, a different account does;
- when no sign-in is stored, or Google refuses the stored one (the consent expired or was revoked, or the OAuth client was deleted, disabled or given a new secret), the run raises `SignInRequiredError` (a `SignInError`), whose message says which and to sign in again. The message never contains a token.
+</Lang>
+
+<Lang only="rust">
+
+The handle a `GoogleDriveClient` signs with. `GoogleDriveClient::from_user_account(&account)` reads the token file at `token_path` (default: the path `sign-in` writes to) when it builds the client:
+
+- the access token is refreshed with the stored refresh token as it expires, and the refreshed token is written back to the file;
+- `email()` is the signed-in account's address, and the client's identity is that address: a refreshed token does not invalidate memoized work, a different account does;
+- when no sign-in is stored, or Google refuses the stored one (the consent expired or was revoked, or the OAuth client was deleted, disabled or given a new secret), the call fails with `SignInError::SignInRequired`, whose message says which and to sign in again. Other sign-in failures are `SignInError::Failed`. `SignInError::of(&error)` recovers the `SignInError` from the SDK's `Error`. The message never contains a token.
+
+</Lang>
+
{/* Rust: rust/sdk/cocoindex/tests/gdrive_user_account.rs */}
<LangTabs>
<Fragment slot="python">
@@ -374,8 +453,6 @@ mount_each!(files.into_iter().map(|file| (file.key(), file)), |file| {
.await?;
```
-`from_user_account` reads the token file now and fails with a message that says how to sign in when no usable sign-in is stored. The sign-in errors are typed: `SignInError::of(&error)` recovers a `SignInError` from the SDK error, `SignInRequired` when a run has no working sign-in (none stored, or Google refused the stored one) and `Failed` for the rest; the message never contains a token. The client's identity is the account's address, so a refreshed token keeps memoized work and a different account invalidates it.
-
</Fragment>
</LangTabs>
@@ -429,23 +506,19 @@ use cocoindex::prelude::*;
cocoindex::context_key!(static GDRIVE: GoogleDriveClient);
-#[cocoindex::function]
-async fn process_file(ctx: &Ctx, file: DriveFile) -> Result<()> {
- let client = ctx.get_key(&GDRIVE)?;
- let text = client.read_text(&file).await?;
+#[cocoindex::function(memo)]
+async fn process_file(_ctx: &Ctx, file: DriveFile) -> Result<()> {
+ let text = file.read_text().await?;
// ... process the file content ...
Ok(())
}
async fn app_main(ctx: Ctx, root_folder_ids: Vec<String>) -> Result<()> {
let source = GoogleDriveSource::new(ctx.get_key(&GDRIVE)?.clone(), root_folder_ids);
- let files = source.list_files().await?;
+ let files = source.items().await?;
println!("indexing {} Google Drive files", files.len());
- mount_each!(files.into_iter().map(|file| (file.key(), file)), |file| {
- process_file(ctx, file)
- })
- .await?;
+ mount_each!(files, |file| process_file(ctx, file)).await?;
Ok(())
}
diff --git a/docs/src/content/docs/connectors/iggy.mdx b/docs/src/content/docs/connectors/iggy.mdx
index 5fb753d6..9df92ab6 100644
--- a/docs/src/content/docs/connectors/iggy.mdx
+++ b/docs/src/content/docs/connectors/iggy.mdx
@@ -25,14 +25,16 @@ from cocoindex.connectors import iggy
<Fragment slot="rust">
```rust
-use cocoindex::connectors::iggy::{self, IggyConsumer, IggyProducer};
+use cocoindex::connectors::iggy::{self, IggyConsumer, IggyProducer, IggyReceivedMessage};
```
-The Rust SDK needs the `iggy` Cargo feature of the `cocoindex` crate. `cocoindex::connectors::iggy::prelude` re-exports the upstream `iggy` crate's prelude (`StreamClient`, `TopicClient`, ...), for creating streams and topics without a direct dependency on that crate.
+`cocoindex::connectors::iggy::prelude` re-exports the upstream `iggy` crate's prelude (`StreamClient`, `TopicClient`, ...), for creating streams and topics without a direct dependency on that crate.
</Fragment>
</LangTabs>
+<Lang only="python">
+
Install the optional dependency:
```bash
@@ -43,6 +45,19 @@ The connector expects an `apache_iggy.IggyClient` that you create, connect, and
provide through your app context. Streams and topics are user-managed:
CocoIndex does not create or drop them.
+</Lang>
+
+<Lang only="rust">
+
+Enable the `iggy` Cargo feature of the `cocoindex` crate.
+
+The connector has two connection handles: an `IggyProducer` for the target,
+provided through your app context, and an `IggyConsumer` that you pass to the
+source functions. Streams and topics are user-managed: CocoIndex does not
+create or drop them.
+
+</Lang>
+
{/* Rust: examples/rust/csv_to_iggy/src/main.rs and rust/sdk/cocoindex/tests/iggy_source.rs */}
<LangTabs>
<Fragment slot="python">
@@ -61,7 +76,7 @@ let producer = IggyProducer::connect("iggy://iggy:iggy@localhost:8090").await?;
let consumer = IggyConsumer::connect("iggy://iggy:iggy@localhost:8090").await?;
```
-The Rust SDK has two connection handles. `IggyProducer` is provided under a `ContextKey` for the target; `IggyConsumer` is passed to the source functions directly. Both connect from a connection string; credentials in the string log in on connect, and `producer.client()` gives the underlying `IggyClient`.
+Both handles connect from a connection string; credentials in the string log in on connect and are stripped from the handle's stable identity. `producer.client()` gives the underlying `IggyClient`. For a client you built and connected yourself, `IggyProducer::from_client(client, state_id)` and `IggyConsumer::from_client(client, state_id)` wrap it; `state_id` is the server's stable identity (its address), never a credential.
</Fragment>
</LangTabs>
@@ -128,12 +143,16 @@ pub struct IggyPollOptions {
}
```
-The Rust stream reads every partition of the topic, so it has no `partition_id`. It has no `initial_high_watermark` either: readiness is reached when every partition is read up to its current offset.
+`IggyTopicStream` is a `LiveStream<IggyReceivedMessage>`. It is also a `LiveMapFeed<String, IggyReceivedMessage>` for `ctx.mount_each_live`: each message becomes a distinct child keyed by its `"{partition}:{offset}"` position. An `IggyReceivedMessage` carries the message's `partition`, `offset`, `id`, `timestamp`, `checksum` and `payload`, with `payload_str()` for the text form.
</Fragment>
</LangTabs>
-`TopicStream.payloads()` adapts the stream to `LiveStream[bytes]` when the
+<RustNote>
+The stream reads every partition of the topic, so it has no `partition_id`. It has no `initial_high_watermark` either: readiness is reached when every partition is read up to the offset it had when the watch started.
+</RustNote>
+
+<Lang only="python">`TopicStream.payloads()` adapts the stream to `LiveStream[bytes]`</Lang><Lang only="rust">`IggyTopicStream::payloads()` adapts the stream to a `LiveStream<Vec<u8>>`</Lang> when the
processing logic only needs message payload bytes.
{/* Rust: rust/sdk/cocoindex/tests/iggy_source.rs */}
@@ -152,19 +171,23 @@ events = iggy.topic_as_stream(
</Fragment>
<Fragment slot="rust">
+```rust
+let events = iggy::topic_as_stream(&consumer, "cocoindex-worker", "orders", "events").payloads();
+```
+
+To process every message in its own component instead, mount the stream itself:
+
```rust
let feed = iggy::topic_as_stream(&consumer, "cocoindex-worker", "orders", "events");
-ctx.mount_each_live(&"stream", feed, move |_ctx, value: Vec<u8>| {
+ctx.mount_each_live(&"stream", feed, move |_ctx, message: IggyReceivedMessage| {
async move {
- println!("{}", String::from_utf8_lossy(&value));
+ println!("{}", message.payload_str());
Ok(())
}
})
.await?;
```
-The Rust SDK has no `LiveStream` type and no `payloads()` view. `IggyTopicStream` is the payload feed itself: a `LiveMapFeed<String, Vec<u8>>` keyed by the message's `"{partition}:{offset}"` position, so every message becomes a distinct child of `ctx.mount_each_live`.
-
</Fragment>
</LangTabs>
@@ -214,27 +237,40 @@ pub fn topic_as_map_with_options(
options: IggySourceOptions,
) -> IggyTopicMap
-pub type IggyKeyFn = Arc<dyn Fn(&[u8]) -> Option<String> + Send + Sync>;
-pub type IggyIsDeletionFn = Arc<dyn Fn(&[u8]) -> bool + Send + Sync>;
+pub type IggyKeyFn = Arc<dyn Fn(&IggyReceivedMessage) -> Option<String> + Send + Sync>;
+pub type IggyIsDeletionFn = Arc<dyn Fn(&IggyReceivedMessage) -> bool + Send + Sync>;
pub struct IggySourceOptions {
/// Partition to consume (default `0`).
pub partition: u32,
pub poll: IggyPollOptions,
- /// Custom deletion predicate over the payload (default: never delete).
+ /// Custom deletion predicate over the message (default: never delete).
pub is_deletion: Option<IggyIsDeletionFn>,
}
```
-`IggyTopicMap` is a `LiveMapFeed<String, Vec<u8>>`: the key is what `key_fn` returns and the value is the message payload. It reads one partition.
+`IggyTopicMap` is a `LiveMapFeed<String, IggyReceivedMessage>`: the key is what `key_fn` returns and the value is the latest message for that key. It reads one partition.
</Fragment>
</LangTabs>
+<Lang only="python">
+
Iggy Python messages do not expose Kafka-style keys or tombstones, so `key` is
required. Return `None` from `key` to skip a message. Pass `is_deletion` if your
payload format has application-level delete events.
+</Lang>
+
+<Lang only="rust">
+
+Iggy messages do not carry Kafka-style keys or tombstones, so `key_fn` is
+required. Return `None` from `key_fn` to skip a message. Set
+`options.is_deletion` if your payload format has application-level delete
+events.
+
+</Lang>
+
{/* Rust: rust/sdk/cocoindex/tests/iggy_source.rs */}
<LangTabs>
<Fragment slot="python">
@@ -263,16 +299,18 @@ items = iggy.topic_as_map(
```rust
/// `key_fn` recovering the key from a `"<key>=<value>"` payload.
fn key_fn() -> iggy::IggyKeyFn {
- Arc::new(|payload: &[u8]| {
- let s = String::from_utf8_lossy(payload);
- s.split_once('=').map(|(k, _)| k.to_string())
+ Arc::new(|message: &IggyReceivedMessage| {
+ message
+ .payload_str()
+ .split_once('=')
+ .map(|(k, _)| k.to_string())
})
}
let feed = iggy::topic_as_map(&consumer, "cocoindex-worker", "orders", "events", key_fn());
-ctx.mount_each_live(&"messages", feed, move |_ctx, value: Vec<u8>| {
+ctx.mount_each_live(&"messages", feed, move |_ctx, message: IggyReceivedMessage| {
async move {
- println!("{}", String::from_utf8_lossy(&value));
+ println!("{}", message.payload_str());
Ok(())
}
})
@@ -309,16 +347,29 @@ The source connector disables Iggy auto-commit and stores offsets after the
downstream readiness handle completes. This mirrors Kafka-style back-pressure:
an offset is stored only after CocoIndex has finished processing the message.
+<Lang only="python">
+
For single-partition topics, the connector can infer the initial high watermark
from Iggy's topic details. For multi-partition topics, pass
`initial_high_watermark` for the consumed partition; the current Python SDK does
not expose per-partition high-watermark callbacks.
-The Rust sources store the consumer group's offset on the server once a polled batch's children have synced, and a later live run resumes from it instead of scanning. The catch-up scan of `topic_as_map` reads the partition log up to its current offset, compacted to the latest payload per key.
+</Lang>
+
+<Lang only="rust">
+
+The consumer group's offset is stored on the server once a polled batch's
+children have synced, and a later live run resumes from it instead of
+scanning. The catch-up scan of `topic_as_map` reads the partition log up to its
+current offset, compacted to the latest message per key. Unless
+`IggyPollOptions::allow_replay` is set, an offset lower than the one stored is
+not stored.
+
+</Lang>
## As Target
-The target connector sends bytes or strings to a user-managed Iggy
+The target connector sends <Lang only="python">bytes or strings</Lang><Lang only="rust">byte payloads</Lang> to a user-managed Iggy
stream/topic/partition.
{/* Rust: examples/rust/csv_to_iggy/src/main.rs */}
@@ -350,12 +401,13 @@ let options = iggy::IggyTopicOptions {
partition: 0,
..Default::default()
};
-let target = iggy::mount_iggy_topic_target(&ctx, &PRODUCER, "orders", "derived-events", options)?;
+let target =
+ iggy::mount_iggy_topic_target(&ctx, &PRODUCER, "orders", "derived-events", options).await?;
target.declare_message(&ctx, "order-123", br#"{"status":"ready"}"#)?;
```
-`mount_iggy_topic_target` is synchronous and returns a ready handle. `declare_message(ctx, key, value)` takes a `&str` key and any byte slice as the value.
+`declare_message(ctx, key, value)` takes a non-empty `&str` key and any byte slice as the value; `declare_message_bytes` takes a binary key. A `&str` key and its UTF-8 bytes are distinct target states.
</Fragment>
</LangTabs>
@@ -384,21 +436,22 @@ target = await iggy.mount_iggy_topic_target(
let options = iggy::IggyTopicOptions {
partition: 0,
// Iggy has no tombstone; emit a delete marker for removed rows.
- deletion_value_fn: Some(Arc::new(|key: &str| {
- format!("{{\"_deleted\":\"{key}\"}}").into_bytes()
+ deletion_value_fn: Some(Arc::new(|key: &[u8]| {
+ format!("{{\"_deleted\":\"{}\"}}", String::from_utf8_lossy(key)).into_bytes()
})),
};
-let target = iggy::mount_iggy_topic_target(&ctx, &PRODUCER, "orders", "derived-events", options)?;
+let target =
+ iggy::mount_iggy_topic_target(&ctx, &PRODUCER, "orders", "derived-events", options).await?;
```
-Without a `deletion_value_fn`, deleting a declared message is an error. The full program is `examples/rust/csv_to_iggy`.
+Without a `deletion_value_fn`, deleting a declared message is an error. The callback receives the key as stored: a `&str` key is its UTF-8 bytes. The full program is `examples/rust/csv_to_iggy`.
</Fragment>
</LangTabs>
### Abandoning a topic
-Removing the topic declaration itself β€” or calling `App.drop()` β€” **abandons**
+Removing the topic declaration itself β€” or calling <Lang only="python">`App.drop()`</Lang><Lang only="rust">`App::drop_state`</Lang> β€” **abandons**
the topic: CocoIndex stops producing to it and sends no deletion messages for
the messages it produced earlier. Changing the stream, topic, or partition in
code abandons the old one the same way. Avoid reusing an abandoned topic in a
@@ -412,6 +465,9 @@ then remove the declaration.
### Target APIs
+`iggy_topic_target()` takes the same arguments as the two functions below and
+builds the topic's target state alone, for <Lang only="python">`coco.mount_target()`</Lang><Lang only="rust">`mount_target` or `declare_target_state_with_child`</Lang>.
+
{/* Rust: rust/sdk/cocoindex/src/connectors/iggy.rs */}
<LangTabs>
<Fragment slot="python">
@@ -450,7 +506,7 @@ pub fn declare_iggy_topic_target(
options: IggyTopicOptions,
) -> Result<IggyTopicTarget>
-pub fn mount_iggy_topic_target(
+pub async fn mount_iggy_topic_target(
ctx: &Ctx,
producer: &ContextKey<IggyProducer>,
stream: impl Into<String>,
@@ -458,13 +514,22 @@ pub fn mount_iggy_topic_target(
options: IggyTopicOptions,
) -> Result<IggyTopicTarget>
+pub fn iggy_topic_target(
+ ctx: &Ctx,
+ producer: &ContextKey<IggyProducer>,
+ stream: impl Into<String>,
+ topic: impl Into<String>,
+ options: IggyTopicOptions,
+) -> Result<TargetState<TopicSpec>>
+
pub struct IggyTopicOptions {
/// Partition to send messages to (default `0`).
pub partition: u32,
/// Value to send when a previously-declared message is removed.
pub deletion_value_fn: Option<DeletionValueFn>,
}
-pub type DeletionValueFn = Arc<dyn Fn(&str) -> Vec<u8> + Send + Sync>;
+/// Takes the key as stored: a `&str` key is its UTF-8 bytes.
+pub type DeletionValueFn = Arc<dyn Fn(&[u8]) -> Vec<u8> + Send + Sync>;
pub fn IggyTopicTarget::declare_message(
&self,
@@ -472,6 +537,13 @@ pub fn IggyTopicTarget::declare_message(
key: &str,
value: impl AsRef<[u8]>,
) -> Result<()>
+
+pub fn IggyTopicTarget::declare_message_bytes(
+ &self,
+ ctx: &Ctx,
+ key: &[u8],
+ value: impl AsRef<[u8]>,
+) -> Result<()>
```
</Fragment>
diff --git a/docs/src/content/docs/connectors/index.mdx b/docs/src/content/docs/connectors/index.mdx
index 31482776..1a8cd2e9 100644
--- a/docs/src/content/docs/connectors/index.mdx
+++ b/docs/src/content/docs/connectors/index.mdx
@@ -8,27 +8,54 @@ description: >
A *connector* links a CocoIndex flow to an external system. It plays one or both of two roles:
- **As source** β€” imports rows into a flow, with change capture so only what actually changed is reprocessed.
-- **As target** β€” exports [target states](/docs/programming_guide/target_state/) from a flow and keeps the external system in sync via incremental upserts and deletions.
+- **As target** β€” exports [target states](../programming_guide/target_state) from a flow and keeps the external system in sync via incremental upserts and deletions.
Some connectors do both. Each page documents the APIs for whichever roles the system supports, under `## As source` / `## As target` sections.
-Every connector listed here also exists in the Rust SDK. Each one lives in `cocoindex::connectors::<name>` behind a Cargo feature of the same name: `cocoindex::connectors::postgres` needs the `postgres` feature, `cocoindex::connectors::qdrant` the `qdrant` feature, and so on. Two names differ: the Google Drive source is `cocoindex::connectors::gdrive` behind the `google_drive` feature, and the local filesystem connector is `cocoindex::resources::fs`, which is always compiled (its live watch needs the `fs_live` feature). Each connector page shows the Rust API next to the Python API.
+<Lang only="rust">
+
+Each connector lives in `cocoindex::connectors::<name>` behind a Cargo feature of the same name: `cocoindex::connectors::postgres` needs the `postgres` feature, `cocoindex::connectors::qdrant` the `qdrant` feature, and so on. Two names differ: the Google Drive source is `cocoindex::connectors::gdrive` behind the `google_drive` feature, and the local filesystem connector is `cocoindex::resources::fs`, which is always compiled (its live watch needs the `fs_live` feature).
+
+</Lang>
+
+<RustNote>
+The Discord source is Python-only: the Rust SDK has no Discord connector, so this page does not list it. See the [Python Discord connector](/docs/connectors/discord/).
+</RustNote>
## Sources
Connectors that feed rows into a flow.
+<Lang only="python">
+
+| Connector | Also a target | Reads from |
+|-----------|---------------|------------|
+| [Local filesystem](./localfs) | βœ… | Local files and directories, with live watch mode |
+| [Amazon S3](./amazon_s3) | | S3 buckets and S3-compatible stores (MinIO, Tigris) |
+| [Azure Blob Storage](./azure_blob) | | Azure Blob Storage containers |
+| [Google Drive](./google_drive) | | Google Drive folders, via a service account or a personal account signed in with OAuth |
+| [OCI Object Storage](./oci_object_storage) | | Oracle Cloud object storage, driven by OCI Streaming events |
+| [Discord](./discord) | | Messages and threads in text, announcement and forum channels |
+| [Postgres](./postgres) | βœ… | PostgreSQL tables via `PgTableSource` |
+| [Kafka](./kafka) | βœ… | Topics as live keyed maps or raw event streams |
+| [Iggy](./iggy) | βœ… | Apache Iggy topics as live streams or maps |
+
+</Lang>
+
+<Lang only="rust">
+
| Connector | Also a target | Reads from |
|-----------|---------------|------------|
-| [Local filesystem](/docs/connectors/localfs/) | βœ… | Local files and directories, with live watch mode |
-| [Amazon S3](/docs/connectors/amazon_s3/) | | S3 buckets and S3-compatible stores (MinIO, Tigris) |
-| [Azure Blob Storage](/docs/connectors/azure_blob/) | | Azure Blob Storage containers |
-| [Google Drive](/docs/connectors/google_drive/) | | Google Drive folders, via a service account or a personal account signed in with OAuth |
-| [OCI Object Storage](/docs/connectors/oci_object_storage/) | | Oracle Cloud object storage, driven by OCI Streaming events |
-| [Discord](/docs/connectors/discord/) | | Messages and threads in text, announcement and forum channels |
-| [Postgres](/docs/connectors/postgres/) | βœ… | PostgreSQL tables via `PgTableSource` |
-| [Kafka](/docs/connectors/kafka/) | βœ… | Topics as live keyed maps or raw event streams |
-| [Iggy](/docs/connectors/iggy/) | βœ… | Apache Iggy topics as live streams or maps |
+| [Local filesystem](./localfs) | βœ… | Local files and directories, with live watch mode |
+| [Amazon S3](./amazon_s3) | | S3 buckets and S3-compatible stores (MinIO, Tigris) |
+| [Azure Blob Storage](./azure_blob) | | Azure Blob Storage containers |
+| [Google Drive](./google_drive) | | Google Drive folders, via a service account or a personal account signed in with OAuth |
+| [OCI Object Storage](./oci_object_storage) | | Oracle Cloud object storage, driven by OCI Streaming events |
+| [Postgres](./postgres) | βœ… | PostgreSQL tables via `read_table` |
+| [Kafka](./kafka) | βœ… | Topics as live keyed maps or raw event streams |
+| [Iggy](./iggy) | βœ… | Apache Iggy topics as live streams or maps |
+
+</Lang>
## Targets
@@ -38,37 +65,37 @@ Connectors that export data out of a flow. They're grouped by the kind of store,
| Connector | Also a source | Notes |
|-----------|---------------|-------|
-| [Postgres](/docs/connectors/postgres/) | βœ… | Relational database with `pgvector` (ivfflat / hnsw) |
-| [Apache Doris](/docs/connectors/doris/) | | Analytical database, HNSW/IVF vector + inverted full-text indexes |
-| [SQLite](/docs/connectors/sqlite/) | | Embedded database, optional vector search via `sqlite-vec` |
-| [Snowflake](/docs/connectors/snowflake/) | | Cloud data warehouse β€” managed DDL, MERGE upserts, incremental deletes |
-| [BigQuery](/docs/connectors/bigquery/) | | Cloud data warehouse with managed DDL, MERGE upserts, incremental deletes |
+| [Postgres](./postgres) | βœ… | Relational database with `pgvector` (ivfflat / hnsw) |
+| [Apache Doris](./doris) | | Analytical database, HNSW/IVF vector + inverted full-text indexes |
+| [SQLite](./sqlite) | | Embedded database, optional vector search via `sqlite-vec` |
+| [Snowflake](./snowflake) | | Cloud data warehouse β€” managed DDL, MERGE upserts, incremental deletes |
+| [BigQuery](./bigquery) | | Cloud data warehouse with managed DDL, MERGE upserts, incremental deletes |
### Vector databases
| Connector | Notes |
|-----------|-------|
-| [LanceDB](/docs/connectors/lancedb/) | Embedded vector DB, vector + full-text (FTS) indexes |
-| [Qdrant](/docs/connectors/qdrant/) | Single, named, and multi-vector points with schemaless payloads |
-| [Turbopuffer](/docs/connectors/turbopuffer/) | Namespaces with single or named vectors |
-| [Valkey](/docs/connectors/valkey/) | Search indexes with vector similarity (HNSW / FLAT) |
-| [zvec](/docs/connectors/zvec/) | Embedded, in-process vector DB with dense and sparse vectors |
+| [LanceDB](./lancedb) | Embedded vector DB, vector + full-text (FTS) indexes |
+| [Qdrant](./qdrant) | Single, named, and multi-vector points with schemaless payloads |
+| [Turbopuffer](./turbopuffer) | Namespaces with single or named vectors |
+| [Valkey](./valkey) | Search indexes with vector similarity (HNSW / FLAT) |
+| [zvec](./zvec) | Embedded, in-process vector DB with dense and sparse vectors |
### Property graph
| Connector | Notes |
|-----------|-------|
-| [Neo4j](/docs/connectors/neo4j/) | Property graph over Bolt β€” node and relationship tables, vector indexes |
-| [FalkorDB](/docs/connectors/falkordb/) | Redis-backed Cypher graph, per-graph multitenancy, vector indexes |
-| [SurrealDB](/docs/connectors/surrealdb/) | Multi-model β€” normal and relation (edge) tables, vector indexes |
+| [Neo4j](./neo4j) | Property graph over Bolt β€” node and relationship tables, vector indexes |
+| [FalkorDB](./falkordb) | Redis-backed Cypher graph, per-graph multitenancy, vector indexes |
+| [SurrealDB](./surrealdb) | Multi-model β€” normal and relation (edge) tables, vector indexes |
### Message streams
| Connector | Also a source | Notes |
|-----------|---------------|-------|
-| [Kafka](/docs/connectors/kafka/) | βœ… | Produce messages as target states with at-least-once semantics |
-| [Iggy](/docs/connectors/iggy/) | βœ… | Produce messages to Apache Iggy topics |
+| [Kafka](./kafka) | βœ… | Produce messages as target states with at-least-once semantics |
+| [Iggy](./iggy) | βœ… | Produce messages to Apache Iggy topics |
## Beyond the built-ins
-If you need a system that isn't listed here, implement a [custom target connector](/docs/advanced_topics/custom_target_connector/) as a building block of your flow.
+If you need a system that isn't listed here, implement a [custom target connector](../advanced_topics/custom_target_connector) as a building block of your flow.
diff --git a/docs/src/content/docs/connectors/kafka.mdx b/docs/src/content/docs/connectors/kafka.mdx
index a3712309..0fa18ffe 100644
--- a/docs/src/content/docs/connectors/kafka.mdx
+++ b/docs/src/content/docs/connectors/kafka.mdx
@@ -26,11 +26,11 @@ from cocoindex.connectors import kafka
use cocoindex::connectors::kafka::{self, KafkaMessage, KafkaProducer};
```
-The Rust SDK needs the `kafka` Cargo feature of the `cocoindex` crate. The Rust connector uses `rskafka`, a pure-Rust client with no `librdkafka` dependency.
-
</Fragment>
</LangTabs>
+<Lang only="python">
+
:::note[Dependencies]
This connector requires additional dependencies. Install with:
@@ -40,14 +40,34 @@ pip install cocoindex[kafka]
:::
+</Lang>
+
+<Lang only="rust">
+
+:::note[Dependencies]
+Enable the `kafka` Cargo feature of the `cocoindex` crate. The connector uses `rskafka`, a pure-Rust client with no `librdkafka` dependency.
+:::
+
+</Lang>
+
## As source
-The `kafka` connector can treat a Kafka topic as a live keyed map β€” each message is an upsert or delete for a key. It returns a [`LiveMapFeed`](../advanced_topics/live_component#livemapfeed-and-livemapview) for use with `mount_each()`. In Rust the feed is a `KafkaTopicMap`, a `LiveMapFeed<String, KafkaMessage>` for `ctx.mount_each_live`.
+The `kafka` connector can treat a Kafka topic as a live keyed map β€” each message is an upsert or delete for a key. It returns a [`LiveMapFeed`](../advanced_topics/live_component#livemapfeed-and-livemapview) for use with <Lang only="python">`mount_each()`</Lang><Lang only="rust">`ctx.mount_each_live`: a `KafkaTopicMap`, which is a `LiveMapFeed<String, KafkaMessage>`</Lang>.
### Setting up a consumer
+<Lang only="python">
+
Create an `AIOConsumer` directly β€” no `ContextKey` needed. The consumer must be **unsubscribed** (the connector handles subscription internally to manage partition rebalance callbacks).
+</Lang>
+
+<Lang only="rust">
+
+Create a `KafkaConsumer` directly β€” no `ContextKey` needed. It is cheap to clone, and one consumer can serve several feeds.
+
+</Lang>
+
{/* Rust: examples/rust/kafka_consume/src/main.rs; SASL/TLS from rust/sdk/SHOWCASE.md, verified against rust/sdk/cocoindex/src/connectors/kafka.rs */}
<LangTabs>
<Fragment slot="python">
@@ -92,13 +112,15 @@ let consumer = kafka::KafkaConsumer::connect_with_options(
.await?;
```
-`KafkaSasl` is `Plain`, `ScramSha256` or `ScramSha512`, each with a `username` and a `password`. `KafkaTls::default()` trusts the Mozilla root certificates; its `ca_cert_pem`, `client_cert_pem` and `client_key_pem` fields add a private CA and a client certificate for mutual TLS.
-
-The Rust client does not speak the consumer-group protocol. A `consumer_group` is CocoIndex's own durable cursor, kept in the app's state database: the broker does not see its lag, and two processes with the same group name do not share partitions.
+`KafkaSasl` is `Plain`, `ScramSha256` or `ScramSha512`, each with a `username` and a `password`. `KafkaTls::default()` trusts the Mozilla root certificates; its `ca_cert_pem`, `client_cert_pem` and `client_key_pem` fields add a private CA and a client certificate for mutual TLS. For a connection setup these options cannot express, build an `rskafka` client yourself and wrap it with `KafkaConsumer::from_client(client, state_id, consumer_group)`, where `state_id` is the cluster's stable identity (for example its bootstrap-server list), never a credential.
</Fragment>
</LangTabs>
+<RustNote>
+The client does not speak the consumer-group protocol. A `consumer_group` is CocoIndex's own durable cursor, kept in the app's state database: the broker does not see its lag, and two processes with the same group name do not share partitions.
+</RustNote>
+
### `topic_as_map()`
{/* Rust: rust/sdk/cocoindex/src/connectors/kafka.rs */}
@@ -138,14 +160,28 @@ pub type IsDeletionFn = Arc<dyn Fn(&KafkaMessage) -> bool + Send + Sync>;
**Parameters:**
+<Lang only="python">
+
- `consumer` β€” An unsubscribed `AIOConsumer`. Auto-commit should be disabled.
- `topic` β€” The topic to consume. To consume several topics, see [Consuming several topics](#consuming-several-topics).
- `is_deletion` β€” Optional predicate `(message: Message) -> bool` for custom deletion detection on non-tombstone messages (see [Deletion handling](#deletion-handling)).
-**Returns:** A `LiveMapFeed[bytes | str, Message]` where each item is keyed by the message key and the value is the full `confluent_kafka.Message` object. The Rust feed is keyed by the message key as a `String` and yields a `KafkaMessage`: its `topic`, `partition`, `offset`, `key`, `value`, `headers` and `timestamp` fields, with `key_str()` and `value_str()` for the text forms.
+**Returns:** A `LiveMapFeed[bytes | str, Message]` where each item is keyed by the message key and the value is the full `confluent_kafka.Message` object.
+
+</Lang>
+
+<Lang only="rust">
+
+- `consumer` β€” A `KafkaConsumer`.
+- `topic` β€” The topic to consume. To consume several topics, see [Consuming several topics](#consuming-several-topics).
+- `options.is_deletion` β€” Optional predicate `Fn(&KafkaMessage) -> bool` for custom deletion detection on non-tombstone messages (see [Deletion handling](#deletion-handling)).
+
+**Returns:** A `KafkaTopicMap`, keyed by the message key as a `String` (lossy UTF-8). Each item is a `KafkaMessage`: its `topic`, `partition`, `offset`, `key`, `value`, `headers` and `timestamp` fields, with `key_str()` and `value_str()` for the text forms.
+
+</Lang>
### Deletion handling
-Messages with `None` value (Kafka tombstones) are **always** treated as deletions. The optional `is_deletion` predicate provides additional deletion logic for non-tombstone messages:
+Messages with <Lang only="python">`None` value</Lang><Lang only="rust">a `None` value</Lang> (Kafka tombstones) are **always** treated as deletions. The optional `is_deletion` predicate provides additional deletion logic for non-tombstone messages:
{/* Rust: rust/sdk/cocoindex/src/connectors/kafka.rs (KafkaSourceOptions) */}
<LangTabs>
@@ -186,9 +222,13 @@ let feed = kafka::topic_as_map_with_options(
### Offset management
-Offsets are committed automatically with at-least-once semantics. Messages are processed in parallel, but an offset is only committed after all earlier messages in the same partition have been fully processed. Messages with `None` keys are logged as errors and skipped.
+Offsets are committed automatically with at-least-once semantics. Messages are processed in parallel, but an offset is only committed after all earlier messages in the same partition have been fully processed. Messages with `None` keys are <Lang only="python">logged as errors and </Lang>skipped.
+
+<Lang only="rust">
-In Rust, a consumer with a `consumer_group` commits the offsets of the records a live run has processed, per partition, to the app's state database under that group name once their child components have synced. The next live run resumes from them. A consumer without a group re-reads the topic on every run. A record with no key is skipped.
+A consumer with a `consumer_group` commits the offsets of the records a live run has processed, per partition, to the app's state database under that group name once their child components have synced. The next live run resumes from them. A consumer without a group re-reads the topic on every run.
+
+</Lang>
### Readiness
@@ -299,7 +339,7 @@ async fn main() -> cocoindex::Result<()> {
### Consuming several topics
-`topic_as_map()` keys each item by its message key alone, so one feed reads one topic. To consume several topics, create one feed per topic, each with its own consumer, and mount each feed under its own `mount_each()` subpath. The subpath keeps the same message key on two topics (for example, `42` on `users` and `42` on `orders`) in two separate components.
+`topic_as_map()` keys each item by its message key alone, so one feed reads one topic. To consume several topics, create one feed per topic<Lang only="python">, each with its own consumer,</Lang> and mount each feed under its own <Lang only="python">`mount_each()`</Lang><Lang only="rust">`mount_each_live`</Lang> subpath. The subpath keeps the same message key on two topics (for example, `42` on `users` and `42` on `orders`) in two separate components.
{/* Rust: examples/rust/kafka_consume/src/main.rs (one feed per topic) */}
<LangTabs>
@@ -344,9 +384,9 @@ The first argument of `mount_each_live` is the subpath; here it is the topic nam
Each topic also writes to its own directory here, because `process_message` names a file by the message key only.
-#### Switching from a list of topics
+<Lang only="python">
-This section applies to the Python SDK. The Rust `topic_as_map` takes one topic.
+#### Switching from a list of topics
Passing a list of topics to `topic_as_map()` is deprecated and emits a `DeprecationWarning`.
@@ -365,6 +405,8 @@ Switching from several topics in a list to one feed per topic changes the item k
3. Change the code to one feed per topic and start the app again. It processes every message the topics still retain.
+</Lang>
+
## As a live stream
Some downstream connectors don't model Kafka messages as a keyed map β€” they treat each message as an opaque event payload (e.g. the [OCI Object Storage](./oci_object_storage#live-bucket-watching) live mode ingests Object Storage event JSON delivered through OCI Streaming). For these, the `kafka` connector exposes a topic as a [`LiveStream`](../advanced_topics/live_component#livestream) β€” CocoIndex's keyless counterpart to `LiveMapFeed`, an opaque sequence of messages with the same readiness and back-pressure machinery but no key/delete semantics.
@@ -404,28 +446,69 @@ ctx.mount_each_live(&"events", feed, move |_ctx, message: KafkaMessage| {
.await?;
```
-The Rust SDK has no `LiveStream` type. `KafkaTopicStream` is a `LiveMapFeed<String, KafkaMessage>` keyed by the record's `"{topic}:{partition}:{offset}"` position, so every record, tombstones included, becomes a distinct child of `mount_each_live`, and nothing is compacted or deleted.
+`KafkaTopicStream` is a `LiveStream<KafkaMessage>`. It is also a `LiveMapFeed<String, KafkaMessage>` for `mount_each_live`, as above: each record becomes a distinct child keyed by its `"{topic}:{partition}:{offset}"` position, tombstones included, and nothing is compacted or deleted. The position keys are stable, so a replayed catch-up reconciles to no-ops.
</Fragment>
</LangTabs>
**Parameters:**
+<Lang only="python">
+
- `consumer` β€” An unsubscribed `AIOConsumer`. Auto-commit should be disabled.
- `topics` β€” Topics to subscribe to.
**Returns:** A `TopicStream` (a `LiveStream[Message]`) that delivers raw `confluent_kafka.Message` objects to its subscriber. [Offset management](#offset-management) and [readiness](#readiness) behave identically to `topic_as_map()`.
+</Lang>
+
+<Lang only="rust">
+
+- `consumer` β€” A `KafkaConsumer`.
+- `topics` β€” Topics to read, across all their partitions.
+
+**Returns:** A `KafkaTopicStream` (a `LiveStream<KafkaMessage>`) that delivers every record, tombstones included, to its subscriber. [Offset management](#offset-management) and [readiness](#readiness) behave identically to `topic_as_map()`.
+
+</Lang>
+
+<Lang only="python">
+
### `TopicStream.payloads()`
+</Lang>
+
+<Lang only="rust">
+
+### `KafkaTopicStream::payloads()`
+
+</Lang>
+
+{/* Rust: rust/sdk/cocoindex/src/connectors/kafka.rs (KafkaTopicStream::payloads) */}
+<LangTabs>
+<Fragment slot="python">
+
```python
def payloads(self) -> LiveStream[bytes]:
```
-A view over the same `TopicStream` that yields each message's value (the byte payload) instead of the full `Message`. Null-valued messages (Kafka tombstones) are filtered out of this view; consumers that need tombstone semantics should subscribe to the `TopicStream` directly.
+</Fragment>
+<Fragment slot="rust">
+
+```rust
+pub fn payloads(self) -> KafkaPayloadStream // a LiveStream<Vec<u8>>
+```
+
+</Fragment>
+</LangTabs>
+
+A view over the same stream that yields each message's value (the byte payload) instead of the full message. Null-valued messages (Kafka tombstones) are filtered out of this view; consumers that need tombstone semantics should subscribe to the <Lang only="python">`TopicStream`</Lang><Lang only="rust">`KafkaTopicStream`</Lang> directly.
This is the typical input for sources that consume opaque event payloads:
+{/* Rust: rust/sdk/SHOWCASE.md (OCI live view); signatures in rust/sdk/cocoindex/src/connectors/oci_object_storage.rs (list_objects_live) */}
+<LangTabs>
+<Fragment slot="python">
+
```python
from confluent_kafka.aio import AIOConsumer
from cocoindex.connectors import kafka, oci_object_storage
@@ -443,21 +526,50 @@ walker = oci_object_storage.list_objects(
)
```
+</Fragment>
+<Fragment slot="rust">
+
+```rust
+let events = kafka::topic_as_stream(&consumer, ["object-storage-events"]).payloads();
+let walker = oci_object_storage::list_objects_live(
+ &client,
+ "my-namespace",
+ "my-bucket",
+ oci_object_storage::ListOptions::default(),
+ events,
+);
+```
+
+The OCI live view acknowledges each event to the stream once the object it names has synced, so the consumer group's offset never passes an unprocessed event.
+
+</Fragment>
+</LangTabs>
+
For a complete app using this pattern, see the [OCI Object Storage live-mode example](./oci_object_storage#example).
-The Rust SDK has no `payloads()` view: filter on `KafkaMessage::value` (`None` for a tombstone) in the `mount_each_live` closure. The Rust OCI live walker, `oci_object_storage::list_objects_live`, takes a `futures::Stream<Item = Vec<u8>>` of event payloads rather than a Kafka feed.
+<Lang only="python">
:::caution
A `TopicStream` (and any `payloads()` view of it) supports at most one active watcher β€” the underlying consumer can hold only one subscription. A second concurrent `watch()` raises `RuntimeError`.
:::
+</Lang>
+
+<Lang only="rust">
+
+:::caution
+A `KafkaTopicStream` (and its `payloads()` view) supports at most one active watcher. A second concurrent `watch` returns an error.
+:::
+
+</Lang>
+
## As target
The `kafka` connector provides target state APIs for producing messages to Kafka topics. Topics are user-managed (CocoIndex does not create or drop topics) β€” CocoIndex only produces messages to them.
### Setting up a producer
-Create a `ContextKey[AIOProducer]` to identify your producer, then provide it in your lifespan:
+<Lang only="python">Create a `ContextKey[AIOProducer]` to identify your producer, then provide it in your lifespan:</Lang><Lang only="rust">Declare a `ContextKey<KafkaProducer>` with `context_key!` to identify your producer, then provide it when you build the environment:</Lang>
:::note
The key name is load-bearing across runs β€” it's the stable identity CocoIndex uses to track target state for topics produced through this key. See [ContextKey as stable identity](../programming_guide/context#contextkey-as-stable-identity) before renaming.
@@ -502,7 +614,7 @@ let app = Environment::builder()
.await?;
```
-`KafkaProducer::connect_with_options(servers, KafkaConnectOptions { sasl, tls })` adds SASL and TLS, as for the consumer. `ensure_topic(topic, num_partitions)` is an explicit helper outside reconciliation; CocoIndex never creates or drops a topic on its own.
+`KafkaProducer::connect_with_options(servers, KafkaConnectOptions { sasl, tls })` adds SASL and TLS, as for the consumer, and `KafkaProducer::from_client(client, state_id)` wraps an `rskafka` client you built. `ensure_topic(topic, num_partitions)` is an explicit helper outside reconciliation; CocoIndex never creates or drops a topic on its own.
</Fragment>
</LangTabs>
@@ -511,7 +623,7 @@ let app = Environment::builder()
#### Topics (parent state)
-Declares a topic as a target state. Returns a `KafkaTopicTarget` for declaring messages.
+Declares a topic as a target state. Returns a `KafkaTopicTarget` for declaring messages. `kafka_topic_target()` takes the same arguments and builds the topic's target state alone, for <Lang only="python">`coco.mount_target()`</Lang><Lang only="rust">`mount_target` or `declare_target_state_with_child`</Lang>; `declare_kafka_topic_target()` and `mount_kafka_topic_target()` wrap it.
{/* Rust: rust/sdk/cocoindex/src/connectors/kafka.rs */}
<LangTabs>
@@ -537,32 +649,52 @@ pub fn declare_kafka_topic_target(
options: KafkaTopicOptions,
) -> Result<KafkaTopicTarget>
-pub fn mount_kafka_topic_target(
+pub async fn mount_kafka_topic_target(
ctx: &Ctx,
producer: &ContextKey<KafkaProducer>,
topic: impl Into<String>,
options: KafkaTopicOptions,
) -> Result<KafkaTopicTarget>
+pub fn kafka_topic_target(
+ ctx: &Ctx,
+ producer: &ContextKey<KafkaProducer>,
+ topic: impl Into<String>,
+ options: KafkaTopicOptions,
+) -> Result<TargetState<TopicSpec>>
+
pub struct KafkaTopicOptions {
pub deletion_value_fn: Option<DeletionValueFn>,
}
-pub type DeletionValueFn = Arc<dyn Fn(&str) -> Vec<u8> + Send + Sync>;
+/// Takes the key as Kafka stores it: a `&str` key is its UTF-8 bytes.
+pub type DeletionValueFn = Arc<dyn Fn(&[u8]) -> Vec<u8> + Send + Sync>;
```
-Both functions are synchronous and return a ready handle: a topic needs no external setup, so there is no pending state to resolve.
-
</Fragment>
</LangTabs>
**Parameters:**
+<Lang only="python">
+
- `producer` β€” A `ContextKey[AIOProducer]` identifying the producer to use.
- `topic` β€” The Kafka topic name.
- `deletion_value_fn` β€” Optional callback that produces a deletion value for a given key (see [Deletion handling](#deletion-handling-1)).
**Returns:** A pending `KafkaTopicTarget`. Use the async convenience wrapper to resolve:
+</Lang>
+
+<Lang only="rust">
+
+- `producer` β€” A `ContextKey<KafkaProducer>` identifying the producer to use.
+- `topic` β€” The Kafka topic name; it must be non-empty.
+- `options.deletion_value_fn` β€” Optional callback that produces a deletion value for a given key (see [Deletion handling](#deletion-handling-1)).
+
+**Returns:** A `KafkaTopicTarget`. `declare_kafka_topic_target` declares the topic in the current component, and its messages resolve at the component's commit; `mount_kafka_topic_target` mounts it in the foreground, so you can declare messages at once:
+
+</Lang>
+
{/* Rust: examples/rust/csv_to_kafka/src/main.rs */}
<LangTabs>
<Fragment slot="python">
@@ -582,7 +714,8 @@ let target = kafka::mount_kafka_topic_target(
&PRODUCER,
"my-topic",
kafka::KafkaTopicOptions::default(),
-)?;
+)
+.await?;
```
</Fragment>
@@ -615,18 +748,34 @@ pub fn KafkaTopicTarget::declare_message(
key: &str,
value: impl AsRef<[u8]>,
) -> Result<()>
-```
-The key is a non-empty `&str`, sent as its UTF-8 bytes; the value is any byte slice, so a `&str`, `String` or `Vec<u8>` works.
+pub fn KafkaTopicTarget::declare_message_bytes(
+ &self,
+ ctx: &Ctx,
+ key: &[u8],
+ value: impl AsRef<[u8]>,
+) -> Result<()>
+```
</Fragment>
</LangTabs>
**Parameters:**
+<Lang only="python">
+
- `key` β€” The message key, used as the stable identity for change detection. A `str` key is sent as its UTF-8 bytes, so `"a"` and `b"a"` are the same Kafka key: declare each key in one form only. If a key changes form between runs (for example, from `"a"` to `b"a"`), CocoIndex publishes the new form and sends no deletion message for the old form, so the record stays.
- `value` β€” The message value.
+</Lang>
+
+<Lang only="rust">
+
+- `key` β€” The message key, used as the stable identity for change detection; it must be non-empty. `declare_message` takes a `&str` and sends its UTF-8 bytes; `declare_message_bytes` takes a binary key. A `&str` key and its UTF-8 bytes are the same Kafka key: declare each key in one form only. If a key changes form between runs (for example, from `"a"` to `b"a"`), CocoIndex publishes the new form and sends no deletion message for the old form, so the record stays.
+- `value` β€” The message value: any byte slice, so a `&str`, `String` or `Vec<u8>` works.
+
+</Lang>
+
CocoIndex fingerprints the value and only produces a message when it has changed since the last run.
### Deletion handling
@@ -636,6 +785,10 @@ While the topic is still declared, a message target state that is no longer decl
- **Without callback** (default): Produces a message with the key and no value (Kafka tombstone).
- **With callback**: Calls `deletion_value_fn(key)` to produce the deletion value.
+<RustNote>
+The callback lives in your process: a run that declares the topic target, or drops the app from a process that did, applies it. `App::drop_state` from a process that never declared the topic target produces tombstones.
+</RustNote>
+
{/* Rust: rust/sdk/cocoindex/tests/kafka_target.rs */}
<LangTabs>
<Fragment slot="python">
@@ -663,15 +816,16 @@ let target = kafka::mount_kafka_topic_target(
&PRODUCER,
"my-topic",
kafka::KafkaTopicOptions::default(),
-)?;
+)
+.await?;
// Custom deletion value
let options = kafka::KafkaTopicOptions {
- deletion_value_fn: Some(Arc::new(|key: &str| {
- format!("deleted:{key}").into_bytes()
+ deletion_value_fn: Some(Arc::new(|key: &[u8]| {
+ format!("deleted:{}", String::from_utf8_lossy(key)).into_bytes()
})),
};
-let target = kafka::mount_kafka_topic_target(&ctx, &PRODUCER, "my-topic", options)?;
+let target = kafka::mount_kafka_topic_target(&ctx, &PRODUCER, "my-topic", options).await?;
```
</Fragment>
@@ -679,7 +833,7 @@ let target = kafka::mount_kafka_topic_target(&ctx, &PRODUCER, "my-topic", option
#### Abandoning a topic
-Removing the topic declaration itself β€” or calling `App.drop()` β€” **abandons** the topic: CocoIndex stops producing to it and emits no tombstones for the messages it produced earlier. Renaming the topic in code abandons the old topic the same way. Avoid reusing an abandoned topic in a later declaration: its stale keys remain and are never tombstoned, and keys you declare again are republished as new even when their values are unchanged.
+Removing the topic declaration itself β€” or calling <Lang only="python">`App.drop()`</Lang><Lang only="rust">`App::drop_state`</Lang> β€” **abandons** the topic: CocoIndex stops producing to it and emits no tombstones for the messages it produced earlier. Renaming the topic in code abandons the old topic the same way. Avoid reusing an abandoned topic in a later declaration: its stale keys remain and are never tombstoned, and keys you declare again are republished as new even when their values are unchanged.
To tombstone everything before abandoning a topic, drain it first:
@@ -744,22 +898,25 @@ app.update_blocking(report_to_stdout=True)
```rust
use cocoindex::connectors::kafka::{self, KafkaProducer};
use cocoindex::prelude::*;
-use cocoindex::resources::fs::FileEntry;
use cocoindex::Environment;
cocoindex::context_key!(static PRODUCER: KafkaProducer);
-/// Parse one CSV file into `(message_key, json_value)` pairs. Memoized: a file
-/// whose content is unchanged since the last run is not re-parsed.
-#[cocoindex::function(memo)]
-async fn process_csv(_ctx: &Ctx, file: FileEntry) -> Result<Vec<(String, String)>> {
- let text = file.content_str()?;
- let mut out = Vec::new();
- // ... push one (key, json) pair per CSV row ...
- Ok(out)
+/// Parse one CSV file and declare one message per row. Memoized on the file:
+/// an unchanged file keeps its messages without re-parsing. The topic target
+/// is one per app, so it is not part of the memo key.
+#[cocoindex::function(memo, memo_key(target = skip))]
+async fn process_csv(ctx: &Ctx, file: &FileEntry, target: &kafka::KafkaTopicTarget) -> Result<()> {
+ let text = file.read_text().await?;
+ // ... for each CSV row, build its message key and JSON value, then:
+ // target.declare_message(ctx, key, value)?;
+ Ok(())
}
async fn index(producer: KafkaProducer, topic: String) -> Result<()> {
+ // The topic is user-managed; create it up front if absent (idempotent).
+ producer.ensure_topic(&topic, 1).await?;
+
let app = Environment::builder()
.db_path(std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")).join(".cocoindex_db"))
.provide_key(&PRODUCER, producer)
@@ -777,17 +934,19 @@ async fn index(producer: KafkaProducer, topic: String) -> Result<()> {
&PRODUCER,
topic,
kafka::KafkaTopicOptions::default(),
- )?;
-
- let files = cocoindex::resources::fs::walk_items("./data", &["**/*.csv"])?;
- let per_file = use_mount_each!(files, |file| process_csv(ctx, file)).await?;
-
- for messages in &per_file {
- for (key, value) in messages {
- target.declare_message(&ctx, key, value)?;
- }
- }
- Ok(())
+ )
+ .await?;
+
+ let files = walk_dir("./data")
+ .path_matcher(PatternFilePathMatcher::include(["**/*.csv"])?)
+ .live();
+ // One processing component per file: each file's messages sync
+ // and clean up with that file.
+ ctx.mount_each_live(&"process_csv", files, move |ctx, file: FileEntry| {
+ let target = target.clone();
+ async move { process_csv(&ctx, &file, &target).await }
+ })
+ .await
}
})
.await?;
@@ -796,7 +955,7 @@ async fn index(producer: KafkaProducer, topic: String) -> Result<()> {
}
```
-The full program is `examples/rust/csv_to_kafka`.
+The full program, with the CSV parsing, is `examples/rust/csv_to_kafka`. `KafkaTopicTarget` is not a memo input, so a memoized function that takes it skips it in its memo key with `memo_key(target = skip)`.
</Fragment>
</LangTabs>
diff --git a/docs/src/content/docs/connectors/localfs.mdx b/docs/src/content/docs/connectors/localfs.mdx
index fc28fd0f..46aab8a9 100644
--- a/docs/src/content/docs/connectors/localfs.mdx
+++ b/docs/src/content/docs/connectors/localfs.mdx
@@ -3,12 +3,16 @@ title: "*Local filesystem* connector"
toc_max_heading_level: 4
description: >
Walk local directories with path-matcher filtering, watch for changes in live
- mode via watchfiles, and write outputs with declare_file() and
+ mode via watchdog, and write outputs with declare_file() and
declare_dir_target() β€” with memo-stable FilePath across project moves.
+rust_description: >
+ Walk local directories with path-matcher filtering, watch for changes in live
+ mode via the platform's native watcher, and write outputs with declare_file()
+ and DirTarget β€” with memo-stable FilePath across project moves.
---
import LangTabs from '../../../components/LangTabs.astro';
-The `localfs` connector provides utilities for reading files from and writing files to the local file system.
+The <Lang only="python">`localfs`</Lang><Lang only="rust">local filesystem</Lang> connector provides utilities for reading files from and writing files to the local file system.
{/* Rust: rust/sdk/cocoindex/tests/fs_target.rs */}
<LangTabs>
@@ -25,19 +29,29 @@ from cocoindex.connectors import localfs
use cocoindex::resources::fs::{self, DirTarget, FileOptions, FilePath};
```
-In the Rust SDK the connector is `cocoindex::resources::fs`. It is always compiled; `cocoindex::prelude::*` exports `DirTarget`, `FileEntry`, `walk_dir`, `walk_items` and `PatternFilePathMatcher`. Live watching (`.live()`) needs the `fs_live` Cargo feature.
+The connector is the module `cocoindex::resources::fs`. It is always compiled; `cocoindex::prelude::*` exports `DirTarget`, `FileEntry`, `walk_dir`, `walk_items` and `PatternFilePathMatcher`. Live watching (`.live()`) needs the `fs_live` Cargo feature.
</Fragment>
</LangTabs>
## Stable memoization with FilePath
-A key feature of the `localfs` connector is [**stable memoization**](../programming_guide/function) through `FilePath`. When you move your entire project directory, memoization keys remain stable as long as you use the same `ContextKey` key string for the base directory.
+A key feature of the <Lang only="python">`localfs`</Lang><Lang only="rust">local filesystem</Lang> connector is [**stable memoization**](../programming_guide/function) through `FilePath`. When you move your entire project directory, memoization keys remain stable as long as you use the same `ContextKey` key <Lang only="python">string</Lang><Lang only="rust">name</Lang> for the base directory.
### Using ContextKey for stable base directories
+<Lang only="python">
+
Define a `ContextKey[pathlib.Path]` with a stable string identifier. Provide the actual path in your app's lifespan, then pass the key directly to `walk_dir()`, `declare_dir_target()`, and related functions.
+</Lang>
+
+<Lang only="rust">
+
+Declare a `ContextKey<PathBuf>` with `context_key!`; its name is the stable identifier. Provide the actual path when you build the environment, then build paths under it with `FilePath::under_context_dir` and pass them to `walk_dir`, `DirTarget::mount` and related functions.
+
+</Lang>
+
{/* Rust: rust/sdk/cocoindex/tests/fs_target.rs */}
<LangTabs>
<Fragment slot="python">
@@ -93,21 +107,31 @@ app.update(move |ctx| async move {
.await?;
```
-A `ContextKey<PathBuf>` is declared with `context_key!` and provided with `provide_key`. `FilePath::under_context_dir(ctx, &KEY, path)` builds the path under it. Every function that takes `impl Into<FilePath>`, such as `walk_dir` and `DirTarget::mount`, accepts that `FilePath`.
+`FilePath::under_context_dir(ctx, &KEY, path)` builds the path under the key's directory. Every function that takes `impl Into<FilePath>`, such as `walk_dir` and `DirTarget::mount`, accepts that `FilePath`.
</Fragment>
</LangTabs>
-When you move your project to a different location, just update the path in `builder.provide()` β€” memoization keys remain the same because they're based on the stable key string (`"source_dir"`), not the filesystem path.
+When you move your project to a different location, just update the path in <Lang only="python">`builder.provide()`</Lang><Lang only="rust">`provide_key`</Lang> β€” memoization keys remain the same because they're based on the stable key <Lang only="python">string (`"source_dir"`)</Lang><Lang only="rust">name (`OUT_DIR`)</Lang>, not the filesystem path.
-Target files are keyed the same way, by the key string and the relative path. Because the base directory isn't part of the key, CocoIndex can't tell when two keys reach the same file. See [One file, one declaration](#one-file-one-declaration).
+Target files are keyed the same way, by the key name and the relative path. Because the base directory isn't part of the key, CocoIndex can't tell when two keys reach the same file. See [One file, one declaration](#one-file-one-declaration).
### FilePath
+<Lang only="python">
+
`FilePath` combines an optional base directory key and a relative path. Passing a `ContextKey[Path]` directly to any localfs function is equivalent to constructing `FilePath(base_dir=key)`.
`FilePath` supports all `pathlib.PurePath` operations:
+</Lang>
+
+<Lang only="rust">
+
+`FilePath` combines an optional base directory key and a relative path. Its path operations are methods:
+
+</Lang>
+
{/* Rust: rust/sdk/cocoindex/src/resources/file.rs (FilePath methods), tests/fs_target.rs */}
<LangTabs>
<Fragment slot="python">
@@ -147,7 +171,7 @@ config_path.parent(); // Some(FilePath pointing to "config")
let abs_path = config_path.resolve(); // std::path::PathBuf
```
-`FilePath::new(path)` builds a path with no base directory. The other `PurePath` operations are `stem`, `suffixes`, `parts`, `with_name`, `with_stem`, `with_suffix`, `relative_to` and `as_posix`.
+`FilePath::new(path)` builds a path with no base directory. The other path operations are `stem`, `suffixes`, `parts`, `with_name`, `with_stem`, `with_suffix`, `relative_to` and `as_posix`.
</Fragment>
</LangTabs>
@@ -156,8 +180,18 @@ See [FilePath](../common_resources/data_types#filepath) in Resource Types for fu
## As source
+<Lang only="python">
+
Use `walk_dir()` to iterate over files in a directory. It returns a `DirWalker` that supports both synchronous and asynchronous iteration.
+</Lang>
+
+<Lang only="rust">
+
+Use `walk_dir()` to list the files in a directory. It returns a `DirWalker`, a builder whose `walk()` and `items()` return the matching files.
+
+</Lang>
+
{/* Rust: rust/sdk/cocoindex/src/resources/fs.rs, examples/rust/text_embedding/src/main.rs */}
<LangTabs>
<Fragment slot="python">
@@ -169,6 +203,7 @@ def walk_dir(
live: bool = False,
recursive: bool = False,
path_matcher: FilePathMatcher | None = None,
+ rescan_interval: datetime.timedelta | None = datetime.timedelta(hours=1),
) -> DirWalker
```
@@ -192,24 +227,51 @@ impl LiveDirWalker {
}
```
-The Rust walker is a builder: `walk_dir(path).recursive(true).path_matcher(matcher)`. The `live` flag becomes the `.live()` method, which turns the walker into a `LiveDirWalker` for `ctx.mount_each_live`; `rescan_interval` is a method on it. `walk()` and `items()` block on the directory walk (a live feed walks on a blocking thread).
-
</Fragment>
</LangTabs>
**Parameters:**
+<Lang only="python">
+
- `path` β€” The root directory path to walk through. Can be a `FilePath`, a `pathlib.Path`, or a `ContextKey[Path]` (equivalent to `FilePath(base_dir=path)`).
- `live` β€” If `True`, `items()` returns a [`LiveMapView`](../advanced_topics/live_component#livemapfeed-and-livemapview) that supports live file watching via `mount_each()`.
- `recursive` β€” If `True`, recursively walk subdirectories.
- `path_matcher` β€” Optional filter for files and directories. See [PatternFilePathMatcher](../common_resources/data_types#patternfilepathmatcher).
+- `rescan_interval` β€” When `live=True`, the interval between periodic full rescans, which recreate the OS-level file watcher and walk the whole directory, as a safety net against events the platform dropped (for example macOS FSEvents silently stopping). Defaults to one hour; `None` disables it. Ignored when `live=False`.
**Returns:** A `DirWalker` that supports async iteration via `async for`.
+</Lang>
+
+<Lang only="rust">
+
+- `path` β€” The root directory to walk: any `impl Into<FilePath>`, such as a `&str`, a `PathBuf`, or a `FilePath` under a context directory.
+- `.recursive(bool)` β€” If `true`, recursively walk subdirectories. Defaults to `false`.
+- `.path_matcher(matcher)` β€” Filter for files and directories. Defaults to match-all. See [PatternFilePathMatcher](../common_resources/data_types#patternfilepathmatcher).
+- `.live()` β€” Turns the walker into a `LiveDirWalker` for `ctx.mount_each_live` (`fs_live` feature). See [Live file watching](#live-file-watching).
+- `.poll_interval(interval)`, `.rescan_interval(interval)` β€” `LiveDirWalker` only: how often to poll where the native watcher is unavailable (default one second), and the interval between periodic full rescans (default one hour; `None` disables it).
+
+**Returns:** A `DirWalker`. `walk()` returns the matching `FileEntry`s and `items()` the `(key, file)` pairs; both block on the directory walk, so call them before the pipeline starts or from a blocking context (a live feed walks on a blocking thread). A missing root directory yields no files; a root that is not a directory is an error.
+
+</Lang>
+
+Symlinked directories are followed, except into a directory that is already an ancestor (a cycle); a symlink to a file is a file. A directory the process can't read, and an entry that vanishes or can't be stat-ed during the walk, are skipped.
+
### Iterating files
+<Lang only="python">
+
`walk_dir()` returns a `DirWalker` that supports async iteration, yielding `File` objects (implementing the [`FileLike`](../common_resources/data_types#filelike) base class):
+</Lang>
+
+<Lang only="rust">
+
+`walk()` returns `FileEntry` values, which implement the [`FileLike`](../common_resources/data_types#filelike) trait:
+
+</Lang>
+
{/* Rust: rust/sdk/cocoindex/src/resources/fs.rs (DirWalker::walk, FileEntry) */}
<LangTabs>
<Fragment slot="python">
@@ -230,16 +292,24 @@ for file in walk_dir("/path/to/documents").recursive(true).walk()? {
}
```
-`walk()` reads the directory and returns a `Vec<FileEntry>`, sorted by relative path. `FileEntry` implements `FileLike`, so `file.read_text().await?` works too; `content()` and `content_str()` are the synchronous reads.
+`walk()` reads the directory and returns a `Vec<FileEntry>`, sorted by relative path. `content()` and `content_str()` are blocking reads. In an async function prefer the `FileLike` reads: `file.read().await?` reads on the runtime's blocking pool and caches the content, returned as a shared `bytes::Bytes`, and `file.read_text().await?` decodes it.
</Fragment>
</LangTabs>
-File I/O runs in a thread pool, keeping the event loop responsive. The Rust walker has no async iteration: `walk()` and `items()` return the full list.
+<Lang only="python">
+
+File I/O runs in a thread pool, keeping the event loop responsive.
+
+</Lang>
+
+<RustNote>
+The walker has no async iteration: `walk()` and `items()` return the full list.
+</RustNote>
### Keyed iteration with `items()`
-`DirWalker.items()` yields keyed `(str, File)` pairs, useful for associating each file with a stable string key (its relative path):
+<Lang only="python">`DirWalker.items()` yields keyed `(str, File)` pairs</Lang><Lang only="rust">`DirWalker::items()` returns keyed `(String, FileEntry)` pairs</Lang>, useful for associating each file with a stable string key (its relative path):
{/* Rust: rust/sdk/cocoindex/src/resources/fs.rs, examples/rust/files_transform/src/main.rs */}
<LangTabs>
@@ -318,8 +388,18 @@ for file in walk_dir("/path/to/project")
### Live file watching
+<Lang only="python">
+
When `live=True`, `items()` returns a [`LiveMapView`](../advanced_topics/live_component#livemapfeed-and-livemapview) instead of a plain `AsyncIterable`. Combined with [`mount_each()`](../programming_guide/processing_component#mount_each), this enables automatic incremental file watching β€” new, modified, and deleted files are processed without a full rescan:
+</Lang>
+
+<Lang only="rust">
+
+`.live()` turns the walker into a `LiveDirWalker`, a [`LiveMapView`](../advanced_topics/live_component#livemapfeed-and-livemapview) plus `LiveMapFeed`. Combined with `ctx.mount_each_live`, this enables automatic incremental file watching β€” new, modified, and deleted files are processed without a full rescan:
+
+</Lang>
+
{/* Rust: examples/rust/text_embedding/src/main.rs */}
<LangTabs>
<Fragment slot="python">
@@ -359,7 +439,7 @@ ctx.mount_each_live(&"files", files, move |ctx, file: FileEntry| {
.await
```
-`.live()` needs the `fs_live` Cargo feature. It returns a `LiveDirWalker`, a `LiveMapView` plus `LiveMapFeed` that follows the directory through the platform's native watcher: each event updates or removes that file's component alone, and a directory that appears is walked. Where the native watcher cannot be set up, it polls instead, every `poll_interval` (default one second). Every `rescan_interval` (default one hour; `None` disables it) it recreates the watcher and walks the whole directory, as a safety net against events the platform dropped. `ctx.mount_each_live(&key, feed, |ctx, file| ...)` mounts one child component per file. See `examples/rust/text_embedding` for the full program.
+`.live()` needs the `fs_live` Cargo feature. The `LiveDirWalker` follows the directory through the platform's native watcher: each event re-runs or removes that file's component alone (whether its work can be skipped is the file's memo decision), a directory that appears is walked, and a directory that moves away removes every file under it. Where the native watcher cannot be set up, it polls instead, every `poll_interval` (default one second). Every `rescan_interval` (default one hour; `None` disables it) it recreates the watcher and walks the whole directory, as a safety net against events the platform dropped. `ctx.mount_each_live(&key, feed, |ctx, file| ...)` mounts one child component per file. See `examples/rust/text_embedding` for the full program.
</Fragment>
</LangTabs>
@@ -475,10 +555,22 @@ pub struct FileOptions {
**Parameters:**
+<Lang only="python">
+
- `path` β€” The filesystem path for the file. Can be a `FilePath`, a `pathlib.Path`, or a `ContextKey[Path]`.
- `content` β€” The file content (bytes or str).
- `create_parent_dirs` β€” If `True`, create parent directories if they don't exist.
+</Lang>
+
+<Lang only="rust">
+
+- `path` β€” The filesystem path for the file: any `impl Into<FilePath>`.
+- `content` β€” The file content, as bytes.
+- `create_parent_dirs` β€” In `FileOptions`, `declare_file_with_options` only. If `true`, create parent directories if they don't exist. Defaults to `false`.
+
+</Lang>
+
**Example:**
{/* Rust: rust/sdk/cocoindex/tests/fs_target.rs */}
@@ -524,6 +616,12 @@ app.update(move |ctx| async move {
Declare a directory target for writing multiple files. Returns a `DirTarget` for declaring files within.
+<Lang only="rust">
+
+The common form is `DirTarget::mount(ctx, dir)`:
+
+</Lang>
+
{/* Rust: rust/sdk/cocoindex/src/resources/fs.rs */}
<LangTabs>
<Fragment slot="python">
@@ -554,18 +652,31 @@ impl DirTarget {
}
```
-`DirTarget::mount(ctx, dir)` is the common form. `declare_dir_target(ctx, dir_target(dir).create_parent_dirs(false))` sets the option. The Rust handle is ready at once: there is no pending state to resolve.
+`declare_dir_target(ctx, dir_target(dir).create_parent_dirs(false))` sets the option.
</Fragment>
</LangTabs>
**Parameters:**
+<Lang only="python">
+
- `path` β€” The filesystem path for the directory. Can be a `FilePath`, a `pathlib.Path`, or a `ContextKey[Path]`.
- `create_parent_dirs` β€” If `True`, create parent directories if they don't exist. Defaults to `True`.
**Returns:** A pending `DirTarget`. Use `await coco.mount_target(...)` or the convenience wrapper `await localfs.mount_dir_target(path)` to resolve.
+</Lang>
+
+<Lang only="rust">
+
+- `dir` β€” The filesystem path for the directory: any `impl Into<FilePath>`.
+- `create_parent_dirs` β€” On `DirTargetState`. If `true`, create parent directories if they don't exist. Defaults to `true`.
+
+**Returns:** A `DirTarget`, ready at once: there is no pending state to resolve. A `DirTarget` is `Clone` and can be an argument of `mount_each!` or a memoized function, as in the [target example](#target-example).
+
+</Lang>
+
### DirTarget.declare_file
Declares a file to be written within the directory.
@@ -607,9 +718,9 @@ target.declare_file_with_options(
**Parameters:**
-- `filename` β€” The name of the file (can include subdirectory path). `.` and `..` segments are normalized, so `./a.txt` and `a.txt` are one file. A name that is absolute or leaves the directory (such as `../a.txt`) raises `ValueError`.
-- `content` β€” The file content (bytes or str).
-- `create_parent_dirs` β€” If `True`, create parent directories within the target directory.
+- `filename` β€” The name of the file (can include subdirectory path). `.` and `..` segments are normalized, so `./a.txt` and `a.txt` are one file. A name that is absolute or leaves the directory (such as `../a.txt`) <Lang only="python">raises `ValueError`</Lang><Lang only="rust">returns an error</Lang>.
+- `content` β€” The file content (<Lang only="python">bytes or str</Lang><Lang only="rust">bytes</Lang>).
+- `create_parent_dirs` β€” <Lang only="rust">In `FileOptions`, `declare_file_with_options` only. </Lang>If <Lang only="python">`True`</Lang><Lang only="rust">`true`</Lang>, create parent directories within the target directory.
### DirTarget.declare_dir_target
@@ -647,7 +758,7 @@ The third argument is `create_parent_dirs`.
**Parameters:**
- `path` β€” The path of the subdirectory (relative to this directory). It's normalized and checked like `filename` above.
-- `create_parent_dirs` β€” If `True`, create parent directories.
+- `create_parent_dirs` β€” If <Lang only="python">`True`</Lang><Lang only="rust">`true`</Lang>, create parent directories.
**Returns:** A `DirTarget` for the subdirectory.
@@ -736,12 +847,12 @@ This example uses plain paths. For a root under a `ContextKey`, build it with `F
### One file, one declaration
-CocoIndex identifies each target file by its key: the `ContextKey` name (none for a path relative to the current directory) and the path under it. The base directory isn't part of the key, which is what lets you move it. The cost is that CocoIndex can't tell when two keys reach the same file on disk. Declare each physical file through exactly one key. The Rust SDK uses the same keys, so the rules below apply to both SDKs.
+CocoIndex identifies each target file by its key: the `ContextKey` name (none for a path relative to the current directory) and the path under it. The base directory isn't part of the key, which is what lets you move it. The cost is that CocoIndex can't tell when two keys reach the same file on disk. Declare each physical file through exactly one key.
Two keys can reach one file in these ways:
-- **Overlapping roots.** Two root directory targets are the same directory, or one is inside the other: under two `ContextKey`s, a `ContextKey` and a plain path, or two paths that reach one directory through a symlink. CocoIndex logs a warning when it applies two such targets. Two `ContextKey`s that point at one base directory are fine if their roots are disjoint, such as `FilePath("foo", base_dir=A)` and `FilePath("bar", base_dir=B)`.
-- **One file named two ways.** Names are normalized, so `./a.txt`, `x/../a.txt` and `a.txt` are one key. A flat path and a nested directory target are not: `target.declare_file("sub/a.txt")` and `target.declare_dir_target("sub")` with `declare_file("a.txt")` are two keys for one file.
+- **Overlapping roots.** Two root directory targets are the same directory, or one is inside the other: under two `ContextKey`s, a `ContextKey` and a plain path, or two paths that reach one directory through a symlink. CocoIndex logs a warning when it applies two such targets. Two `ContextKey`s that point at one base directory are fine if their roots are disjoint, such as <Lang only="python">`FilePath("foo", base_dir=A)` and `FilePath("bar", base_dir=B)`</Lang><Lang only="rust">`FilePath::under_context_dir(&ctx, &A, "foo")?` and `FilePath::under_context_dir(&ctx, &B, "bar")?`</Lang>.
+- **One file named two ways.** Names are normalized, so `./a.txt`, `x/../a.txt` and `a.txt` are one key. A flat path and a nested directory target are not: <Lang only="python">`target.declare_file("sub/a.txt")` and `target.declare_dir_target("sub")` with `declare_file("a.txt")`</Lang><Lang only="rust">`target.declare_file(&ctx, "sub/a.txt", ..)` and `target.declare_dir_target(&ctx, "sub", false)` with `declare_file(&ctx, "a.txt", ..)`</Lang> are two keys for one file.
- **Names that differ only in case** on a case-insensitive file system (the default on macOS and Windows). There, `A.txt` and `a.txt` are one file.
- **A file declared through a path into a directory target.** If `sub` is a directory target and its parent also declares `sub/a.txt`, removing the `sub` directory target removes `sub/a.txt` too. Removing a directory target removes the whole directory.
@@ -749,4 +860,4 @@ You can switch a file from one key to another in one update if the processing co
The opposite switch, from a nested directory target to flat paths, takes two updates. A nested directory target is resolved in its own processing component, so CocoIndex removes it after it writes the flat files, and that removal deletes them. Remove the directory target and run an update first. Then declare the flat files and run a second update.
-A relative path, such as `pathlib.Path("out")`, uses the current directory as its base, and the key holds only the relative path. If you run the app from another directory, the same keys reach other files: CocoIndex doesn't write unchanged files to the new place, and the old files stay. Run the app from one directory, or use a `ContextKey`.
+A relative path, such as <Lang only="python">`pathlib.Path("out")`</Lang><Lang only="rust">`PathBuf::from("out")`</Lang>, uses the current directory as its base, and the key holds only the relative path. If you run the app from another directory, the same keys reach other files: CocoIndex doesn't write unchanged files to the new place, and the old files stay. Run the app from one directory, or use a `ContextKey`.