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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
192 changes: 192 additions & 0 deletions Sources/Storage/StorageVectorsClient.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,192 @@
//
// StorageVectorsClient.swift
// Storage
//
// Created by Guilherme Souza on 27/07/26.
//

public import Foundation
import HTTPTypes

#if canImport(FoundationNetworking)
import FoundationNetworking
#endif

/// A client for managing Supabase Storage's alpha "vector buckets" feature (`storage.vectors`).
///
/// Obtain an instance via ``SupabaseStorageClient/vectors``:
///
/// ```swift
/// try await client.storage.vectors.createBucket("documents")
/// let buckets = try await client.storage.vectors.listBuckets().vectorBuckets
/// ```
///
/// - Warning: Vector buckets are a public alpha feature of Supabase Storage and this API is
/// experimental — it may change in a breaking way, or be unavailable on your project, until it
/// reaches general availability. Opt in with `@_spi(Experimental) import Supabase`.
///
/// ## Topics
///
/// ### Managing vector buckets
///
/// - ``createBucket(_:)``
/// - ``getBucket(_:)``
/// - ``listBuckets(prefix:maxResults:nextToken:)``
/// - ``deleteBucket(_:)``
@_spi(Experimental)
public struct StorageVectorsClient: Sendable {
private let api: StorageApi

init(api: StorageApi) {
self.api = api
}

/// Creates a new vector bucket.
///
/// ```swift
/// try await client.storage.vectors.createBucket("documents")
/// ```
///
/// - Warning: Experimental. See ``StorageVectorsClient``.
///
/// - Parameter name: The name of the vector bucket to create.
/// - Throws: ``StorageError`` when the API rejects the request.
public func createBucket(_ name: String) async throws {
try await api.execute(
HTTPRequest(
url: api.configuration.url.appendingPathComponent("vector/CreateVectorBucket"),
method: .post,
body: JSONEncoder.unconfiguredEncoder.encode(VectorBucketNameBody(vectorBucketName: name))
)
)
}

/// Retrieves the details of an existing vector bucket.
///
/// ```swift
/// let bucket = try await client.storage.vectors.getBucket("documents")
/// print(bucket.vectorBucketName)
/// ```
///
/// - Warning: Experimental. See ``StorageVectorsClient``.
///
/// - Parameter name: The name of the vector bucket to fetch.
/// - Returns: The matching ``VectorBucket``.
/// - Throws: ``StorageError`` when the API rejects the request.
public func getBucket(_ name: String) async throws -> VectorBucket {
let response: GetVectorBucketResponseBody = try await api.execute(
HTTPRequest(
url: api.configuration.url.appendingPathComponent("vector/GetVectorBucket"),
method: .post,
body: JSONEncoder.unconfiguredEncoder.encode(VectorBucketNameBody(vectorBucketName: name))
)
)
.decoded(decoder: .supabase())
return response.vectorBucket
}

/// Lists the vector buckets in the project, optionally filtered by name prefix.
///
/// Results are paginated: pass the ``ListVectorBucketsResponse/nextToken`` of a previous response
/// as `nextToken` to fetch the following page.
///
/// ```swift
/// let page = try await client.storage.vectors.listBuckets(prefix: "docs")
/// for bucket in page.vectorBuckets {
/// print(bucket.vectorBucketName)
/// }
/// ```
///
/// - Warning: Experimental. See ``StorageVectorsClient``.
///
/// - Parameters:
/// - prefix: Returns only buckets whose name starts with this prefix. Pass `nil` for all buckets.
/// - maxResults: The maximum number of buckets to return in this page.
/// - nextToken: The pagination token from a previous response.
/// - Returns: A page of buckets, plus the token for the next page when more results exist.
/// - Throws: ``StorageError`` when the API rejects the request.
public func listBuckets(
prefix: String? = nil,
maxResults: Int? = nil,
nextToken: String? = nil
) async throws -> ListVectorBucketsResponse {
let response: ListVectorBucketsResponseBody = try await api.execute(
HTTPRequest(
url: api.configuration.url.appendingPathComponent("vector/ListVectorBuckets"),
method: .post,
body: JSONEncoder.unconfiguredEncoder.encode(
VectorBucketListBody(maxResults: maxResults, nextToken: nextToken, prefix: prefix)
)
)
)
.decoded(decoder: .supabase())
return ListVectorBucketsResponse(
vectorBuckets: response.vectorBuckets,
nextToken: response.nextToken
)
}

/// Deletes a vector bucket.
///
/// ```swift
/// try await client.storage.vectors.deleteBucket("documents")
/// ```
///
/// - Warning: Experimental. See ``StorageVectorsClient``.
///
/// - Parameter name: The name of the vector bucket to delete.
/// - Throws: ``StorageError`` when the API rejects the request.
public func deleteBucket(_ name: String) async throws {
try await api.execute(
HTTPRequest(
url: api.configuration.url.appendingPathComponent("vector/DeleteVectorBucket"),
method: .post,
body: JSONEncoder.unconfiguredEncoder.encode(VectorBucketNameBody(vectorBucketName: name))
)
)
}
}

private struct VectorBucketNameBody: Encodable {
var vectorBucketName: String
}

private struct VectorBucketListBody: Encodable {
var maxResults: Int?
var nextToken: String?
var prefix: String?
}

private struct GetVectorBucketResponseBody: Decodable {
var vectorBucket: VectorBucket
}

private struct ListVectorBucketsResponseBody: Decodable {
var vectorBuckets: [VectorBucket]
var nextToken: String?
}

/// A vector bucket, as returned by ``StorageVectorsClient``.
///
/// - Warning: Experimental. See ``StorageVectorsClient``.
@_spi(Experimental)
public struct VectorBucket: Codable, Sendable, Hashable {
/// The name of the vector bucket.
public var vectorBucketName: String

/// UNIX timestamp (seconds) of when the bucket was created, if known.
public var creationTime: TimeInterval?
}

/// A page of vector buckets, as returned by
/// ``StorageVectorsClient/listBuckets(prefix:maxResults:nextToken:)``.
///
/// - Warning: Experimental. See ``StorageVectorsClient``.
@_spi(Experimental)
public struct ListVectorBucketsResponse: Sendable {
/// The buckets in this page.
public var vectorBuckets: [VectorBucket]

/// The pagination token to pass to fetch the next page, or `nil` when there are no more results.
public var nextToken: String?
}
14 changes: 14 additions & 0 deletions Sources/Storage/SupabaseStorage.swift
Original file line number Diff line number Diff line change
Expand Up @@ -64,8 +64,8 @@
public init(
url: URL,
headers: [String: String],
encoder: JSONEncoder = .defaultStorageEncoder,

Check warning on line 67 in Sources/Storage/SupabaseStorage.swift

View workflow job for this annotation

GitHub Actions / xcodebuild (macOS latest) (test, MACOS, 26.4)

'defaultStorageEncoder' is deprecated: Access to storage encoder is going to be removed.

Check warning on line 67 in Sources/Storage/SupabaseStorage.swift

View workflow job for this annotation

GitHub Actions / xcodebuild (macOS latest) (test, MACOS, 26.4)

'defaultStorageEncoder' is deprecated: Access to storage encoder is going to be removed.

Check warning on line 67 in Sources/Storage/SupabaseStorage.swift

View workflow job for this annotation

GitHub Actions / xcodebuild (legacy) (MAC_CATALYST, 16.4)

'defaultStorageEncoder' is deprecated: Access to storage encoder is going to be removed.

Check warning on line 67 in Sources/Storage/SupabaseStorage.swift

View workflow job for this annotation

GitHub Actions / xcodebuild (legacy) (MAC_CATALYST, 16.4)

'defaultStorageEncoder' is deprecated: Access to storage encoder is going to be removed.

Check warning on line 67 in Sources/Storage/SupabaseStorage.swift

View workflow job for this annotation

GitHub Actions / xcodebuild (macOS latest) (MACOS, 26.4)

'defaultStorageEncoder' is deprecated: Access to storage encoder is going to be removed.

Check warning on line 67 in Sources/Storage/SupabaseStorage.swift

View workflow job for this annotation

GitHub Actions / xcodebuild (macOS latest) (MACOS, 26.4)

'defaultStorageEncoder' is deprecated: Access to storage encoder is going to be removed.

Check warning on line 67 in Sources/Storage/SupabaseStorage.swift

View workflow job for this annotation

GitHub Actions / xcodebuild (legacy) (test, MAC_CATALYST, 16.4)

'defaultStorageEncoder' is deprecated: Access to storage encoder is going to be removed.

Check warning on line 67 in Sources/Storage/SupabaseStorage.swift

View workflow job for this annotation

GitHub Actions / xcodebuild (legacy) (test, MAC_CATALYST, 16.4)

'defaultStorageEncoder' is deprecated: Access to storage encoder is going to be removed.

Check warning on line 67 in Sources/Storage/SupabaseStorage.swift

View workflow job for this annotation

GitHub Actions / xcodebuild (legacy) (MACOS, 16.4)

'defaultStorageEncoder' is deprecated: Access to storage encoder is going to be removed.

Check warning on line 67 in Sources/Storage/SupabaseStorage.swift

View workflow job for this annotation

GitHub Actions / xcodebuild (legacy) (MACOS, 16.4)

'defaultStorageEncoder' is deprecated: Access to storage encoder is going to be removed.

Check warning on line 67 in Sources/Storage/SupabaseStorage.swift

View workflow job for this annotation

GitHub Actions / Examples (UserManagement)

'defaultStorageEncoder' is deprecated: Access to storage encoder is going to be removed.

Check warning on line 67 in Sources/Storage/SupabaseStorage.swift

View workflow job for this annotation

GitHub Actions / Examples (UserManagement)

'defaultStorageEncoder' is deprecated: Access to storage encoder is going to be removed.

Check warning on line 67 in Sources/Storage/SupabaseStorage.swift

View workflow job for this annotation

GitHub Actions / Examples (SlackClone)

'defaultStorageEncoder' is deprecated: Access to storage encoder is going to be removed.

Check warning on line 67 in Sources/Storage/SupabaseStorage.swift

View workflow job for this annotation

GitHub Actions / Examples (SlackClone)

'defaultStorageEncoder' is deprecated: Access to storage encoder is going to be removed.

Check warning on line 67 in Sources/Storage/SupabaseStorage.swift

View workflow job for this annotation

GitHub Actions / Examples (Examples)

'defaultStorageEncoder' is deprecated: Access to storage encoder is going to be removed.

Check warning on line 67 in Sources/Storage/SupabaseStorage.swift

View workflow job for this annotation

GitHub Actions / Examples (Examples)

'defaultStorageEncoder' is deprecated: Access to storage encoder is going to be removed.

Check warning on line 67 in Sources/Storage/SupabaseStorage.swift

View workflow job for this annotation

GitHub Actions / xcodebuild (macOS latest) (test, IOS, 26.4)

'defaultStorageEncoder' is deprecated: Access to storage encoder is going to be removed.

Check warning on line 67 in Sources/Storage/SupabaseStorage.swift

View workflow job for this annotation

GitHub Actions / xcodebuild (macOS latest) (test, IOS, 26.4)

'defaultStorageEncoder' is deprecated: Access to storage encoder is going to be removed.
decoder: JSONDecoder = .defaultStorageDecoder,

Check warning on line 68 in Sources/Storage/SupabaseStorage.swift

View workflow job for this annotation

GitHub Actions / xcodebuild (macOS latest) (test, MACOS, 26.4)

'defaultStorageDecoder' is deprecated: Access to storage decoder is going to be removed.

Check warning on line 68 in Sources/Storage/SupabaseStorage.swift

View workflow job for this annotation

GitHub Actions / xcodebuild (macOS latest) (test, MACOS, 26.4)

'defaultStorageDecoder' is deprecated: Access to storage decoder is going to be removed.

Check warning on line 68 in Sources/Storage/SupabaseStorage.swift

View workflow job for this annotation

GitHub Actions / xcodebuild (legacy) (MAC_CATALYST, 16.4)

'defaultStorageDecoder' is deprecated: Access to storage decoder is going to be removed.

Check warning on line 68 in Sources/Storage/SupabaseStorage.swift

View workflow job for this annotation

GitHub Actions / xcodebuild (legacy) (MAC_CATALYST, 16.4)

'defaultStorageDecoder' is deprecated: Access to storage decoder is going to be removed.

Check warning on line 68 in Sources/Storage/SupabaseStorage.swift

View workflow job for this annotation

GitHub Actions / xcodebuild (macOS latest) (MACOS, 26.4)

'defaultStorageDecoder' is deprecated: Access to storage decoder is going to be removed.

Check warning on line 68 in Sources/Storage/SupabaseStorage.swift

View workflow job for this annotation

GitHub Actions / xcodebuild (macOS latest) (MACOS, 26.4)

'defaultStorageDecoder' is deprecated: Access to storage decoder is going to be removed.

Check warning on line 68 in Sources/Storage/SupabaseStorage.swift

View workflow job for this annotation

GitHub Actions / xcodebuild (legacy) (test, MAC_CATALYST, 16.4)

'defaultStorageDecoder' is deprecated: Access to storage decoder is going to be removed.

Check warning on line 68 in Sources/Storage/SupabaseStorage.swift

View workflow job for this annotation

GitHub Actions / xcodebuild (legacy) (test, MAC_CATALYST, 16.4)

'defaultStorageDecoder' is deprecated: Access to storage decoder is going to be removed.

Check warning on line 68 in Sources/Storage/SupabaseStorage.swift

View workflow job for this annotation

GitHub Actions / xcodebuild (legacy) (MACOS, 16.4)

'defaultStorageDecoder' is deprecated: Access to storage decoder is going to be removed.

Check warning on line 68 in Sources/Storage/SupabaseStorage.swift

View workflow job for this annotation

GitHub Actions / xcodebuild (legacy) (MACOS, 16.4)

'defaultStorageDecoder' is deprecated: Access to storage decoder is going to be removed.

Check warning on line 68 in Sources/Storage/SupabaseStorage.swift

View workflow job for this annotation

GitHub Actions / Examples (UserManagement)

'defaultStorageDecoder' is deprecated: Access to storage decoder is going to be removed.

Check warning on line 68 in Sources/Storage/SupabaseStorage.swift

View workflow job for this annotation

GitHub Actions / Examples (UserManagement)

'defaultStorageDecoder' is deprecated: Access to storage decoder is going to be removed.

Check warning on line 68 in Sources/Storage/SupabaseStorage.swift

View workflow job for this annotation

GitHub Actions / Examples (SlackClone)

'defaultStorageDecoder' is deprecated: Access to storage decoder is going to be removed.

Check warning on line 68 in Sources/Storage/SupabaseStorage.swift

View workflow job for this annotation

GitHub Actions / Examples (SlackClone)

'defaultStorageDecoder' is deprecated: Access to storage decoder is going to be removed.

Check warning on line 68 in Sources/Storage/SupabaseStorage.swift

View workflow job for this annotation

GitHub Actions / Examples (Examples)

'defaultStorageDecoder' is deprecated: Access to storage decoder is going to be removed.

Check warning on line 68 in Sources/Storage/SupabaseStorage.swift

View workflow job for this annotation

GitHub Actions / Examples (Examples)

'defaultStorageDecoder' is deprecated: Access to storage decoder is going to be removed.

Check warning on line 68 in Sources/Storage/SupabaseStorage.swift

View workflow job for this annotation

GitHub Actions / xcodebuild (macOS latest) (test, IOS, 26.4)

'defaultStorageDecoder' is deprecated: Access to storage decoder is going to be removed.

Check warning on line 68 in Sources/Storage/SupabaseStorage.swift

View workflow job for this annotation

GitHub Actions / xcodebuild (macOS latest) (test, IOS, 26.4)

'defaultStorageDecoder' is deprecated: Access to storage decoder is going to be removed.
session: StorageHTTPSession = .init(),
logger: (any SupabaseLogger)? = nil,
useNewHostname: Bool = false
Expand Down Expand Up @@ -103,6 +103,7 @@
/// ### Accessing buckets
///
/// - ``from(_:)``
/// - ``vectors``
///
/// ### Bucket management
///
Expand All @@ -123,4 +124,17 @@
public func from(_ id: String) -> StorageFileApi {
StorageFileApi(bucketId: id, configuration: configuration)
}

/// A client for managing vector buckets.
///
/// ```swift
/// try await client.storage.vectors.createBucket("documents")
/// let buckets = try await client.storage.vectors.listBuckets().vectorBuckets
/// ```
///
/// - Warning: Experimental. See ``StorageVectorsClient``.
@_spi(Experimental)
public var vectors: StorageVectorsClient {
StorageVectorsClient(api: self)
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
//
// StorageVectorsClientIntegrationTests.swift
//
//
// Created by Guilherme Souza on 06/08/26.
//

import Foundation
import InlineSnapshotTesting
@_spi(Experimental) import Storage
import Testing

@Suite(.enabled(if: ProcessInfo.processInfo.environment["INTEGRATION_TESTS"] != nil))
struct StorageVectorsClientIntegrationTests {
Comment on lines +13 to +14

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

printf 'Files matching StorageVectorsClientIntegrationTests.swift:\n'
fd -a 'StorageVectorsClientIntegrationTests.swift' . || true

printf '\nRelevant file contents:\n'
f="$(fd 'StorageVectorsClientIntegrationTests.swift' . | head -n 1)"
if [ -n "${f:-}" ]; then
  wc -l "$f"
  sed -n '1,140p' "$f" | cat -n
fi

printf '\nSearch for test-vector-bucket usages:\n'
rg -n 'test-vector-bucket|vectorBucket_CRUD|listBucketsWithPrefix|`@Suite`|`@Test`' .

Repository: supabase/supabase-swift

Length of output: 50379


🌐 Web query:

Swift Testing @suite .serialized trait documentation

💡 Result:

The.serialized trait in the Swift Testing framework is a trait used to control the execution order of tests by enforcing sequential (serial) rather than parallel execution [1][2]. Key characteristics and usage include: Application: It can be applied to both individual @Test functions and entire @Suite types [2][3]. Parameterized Tests: When applied to a parameterized test function, it ensures that all cases of that test run serially [2][4]. Suite Scope: When applied to a @Suite, the trait is applied recursively; all test functions and sub-suites contained within that suite will be executed serially [2][5]. Non-parameterized Tests: When applied to a non-parameterized, single test function, it generally has no effect, as those tests are naturally serial with respect to their internal code [2][4]. Scope of Effect: This trait only affects the serialization of the tests to which it is applied (or its children); it does not affect the execution of a test relative to its peers in unrelated suites or the global test execution [2][5]. Global Context: This trait is ignored if test parallelization is disabled globally (e.g., by passing the --no-parallel flag to the swift test command) [2][5]. The trait is available as a public API in the Testing framework and is documented as part of the ParallelizationTrait documentation [1][2][3].

Citations:


Serialize test-vector-bucket integration tests.

vectorBucket_CRUD and listBucketsWithPrefix share the same bucket name. Swift Testing can run suite tests concurrently unless the suite is serialized, so one test can delete or create the bucket while another test reads it.

Proposed fix
-@Suite(.enabled(if: ProcessInfo.processInfo.environment["INTEGRATION_TESTS"] != nil))
+@Suite(.enabled(if: ProcessInfo.processInfo.environment["INTEGRATION_TESTS"] != nil), .serialized)
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
@Suite(.enabled(if: ProcessInfo.processInfo.environment["INTEGRATION_TESTS"] != nil))
struct StorageVectorsClientIntegrationTests {
`@Suite`(.enabled(if: ProcessInfo.processInfo.environment["INTEGRATION_TESTS"] != nil), .serialized)
struct StorageVectorsClientIntegrationTests {
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@Tests/IntegrationTests/StorageVectorsClientIntegrationTests.swift` around
lines 13 - 14, Mark the StorageVectorsClientIntegrationTests suite as serialized
so vectorBucket_CRUD and listBucketsWithPrefix cannot run concurrently against
the shared test-vector-bucket resource. Keep the existing INTEGRATION_TESTS
enablement condition unchanged.

let vectors = SupabaseStorageClient(
configuration: StorageClientConfiguration(
url: URL(string: "\(DotEnv.SUPABASE_URL)/storage/v1")!,
headers: [
"Authorization": "Bearer \(DotEnv.SUPABASE_SECRET_KEY)"
],
logger: nil
)
).vectors

init() async throws {
// Clean up test-vector-bucket if it exists from a previous failed run
// to make tests idempotent
try? await vectors.deleteBucket("test-vector-bucket")
}

@Test
func vectorBucket_CRUD() async throws {
let bucketName = "test-vector-bucket"

var page = try await vectors.listBuckets()
#expect(!page.vectorBuckets.contains { $0.vectorBucketName == bucketName })

try await vectors.createBucket(bucketName)

let bucket = try await vectors.getBucket(bucketName)
#expect(bucket.vectorBucketName == bucketName)

page = try await vectors.listBuckets()
#expect(page.vectorBuckets.contains { $0.vectorBucketName == bucketName })

try await vectors.deleteBucket(bucketName)

page = try await vectors.listBuckets()
#expect(!page.vectorBuckets.contains { $0.vectorBucketName == bucketName })
}

@Test
func listBucketsWithPrefix() async throws {
let bucketName = "test-vector-bucket"
try await vectors.createBucket(bucketName)

let matching = try await vectors.listBuckets(prefix: "test-vector-")
#expect(matching.vectorBuckets.contains { $0.vectorBucketName == bucketName })

let nonMatching = try await vectors.listBuckets(prefix: "no-such-prefix-")
#expect(!nonMatching.vectorBuckets.contains { $0.vectorBucketName == bucketName })

try await vectors.deleteBucket(bucketName)
}

@Test
func getBucketWithWrongName() async {
do {
_ = try await vectors.getBucket("not-exist-bucket")
Issue.record("Unexpected success")
} catch {
assertInlineSnapshot(of: error, as: .dump) {
"""
▿ StorageError
▿ error: Optional<String>
- some: "NotFoundException"
- message: "resource \\"not-exist-bucket\\" not found"
▿ statusCode: Optional<String>
- some: "404"

"""
}
}
}
}
Loading
Loading