diff --git a/Package.swift b/Package.swift index ae5d0737..31caf069 100644 --- a/Package.swift +++ b/Package.swift @@ -127,6 +127,7 @@ let package = Package( name: "RealtimeTests", dependencies: [ "Realtime", + "PostgREST", "TestHelpers", .product(name: "CustomDump", package: "swift-custom-dump"), ] diff --git a/Sources/PostgREST/PostgrestClient.swift b/Sources/PostgREST/PostgrestClient.swift index 4172c7fa..0beba6c0 100644 --- a/Sources/PostgREST/PostgrestClient.swift +++ b/Sources/PostgREST/PostgrestClient.swift @@ -3,6 +3,7 @@ import ConcurrencyExtras import Foundation public typealias PostgrestError = _Helpers.PostgrestError +public typealias AnyJSON = _Helpers.AnyJSON #if canImport(FoundationNetworking) import FoundationNetworking diff --git a/Sources/Realtime/V2/RealtimeClientV2.swift b/Sources/Realtime/V2/RealtimeClientV2.swift index eca2b36f..7bf05eda 100644 --- a/Sources/Realtime/V2/RealtimeClientV2.swift +++ b/Sources/Realtime/V2/RealtimeClientV2.swift @@ -15,6 +15,8 @@ import Foundation let NSEC_PER_SEC: UInt64 = 1000000000 #endif +public typealias JSONObject = _Helpers.JSONObject + public actor RealtimeClientV2 { public struct Configuration: Sendable { var url: URL diff --git a/Tests/RealtimeTests/RealtimeIntegrationTests.swift b/Tests/RealtimeTests/RealtimeIntegrationTests.swift new file mode 100644 index 00000000..4ca7abe7 --- /dev/null +++ b/Tests/RealtimeTests/RealtimeIntegrationTests.swift @@ -0,0 +1,228 @@ +// +// RealtimeIntegrationTests.swift +// +// +// Created by Guilherme Souza on 27/03/24. +// + +import ConcurrencyExtras +import CustomDump +import PostgREST +@testable import Realtime +import XCTest + +final class RealtimeIntegrationTests: XCTestCase { + let realtime = RealtimeClientV2( + config: RealtimeClientV2.Configuration( + url: URL(string: "http://localhost:54321/realtime/v1")!, + apiKey: "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZS1kZW1vIiwicm9sZSI6ImFub24iLCJleHAiOjE5ODM4MTI5OTZ9.CRXP1A7WOeoJeXxjNni43kdQwgnWNReilDMblYTn_I0" + ) + ) + + let db = PostgrestClient( + url: URL(string: "http://localhost:54321/rest/v1")!, + headers: [ + "apikey": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZS1kZW1vIiwicm9sZSI6InNlcnZpY2Vfcm9sZSIsImV4cCI6MTk4MzgxMjk5Nn0.EGIM96RAZx35lJzdJsyH-qQwv8Hdp7fsn3W0YpN81IU", + ], + logger: nil + ) + + func testBroadcast() async throws { + let expectation = expectation(description: "receivedBroadcastMessages") + expectation.expectedFulfillmentCount = 3 + + let channel = await realtime.channel("integration") { + $0.broadcast.receiveOwnBroadcasts = true + } + + let receivedMessages = LockIsolated<[JSONObject]>([]) + + Task { + for await message in await channel.broadcast(event: "test") { + receivedMessages.withValue { + $0.append(message) + } + expectation.fulfill() + } + } + + await Task.megaYield() + + await channel.subscribe() + + struct Message: Codable { + var value: Int + } + + try await channel.broadcast(event: "test", message: Message(value: 1)) + try await channel.broadcast(event: "test", message: Message(value: 2)) + try await channel.broadcast(event: "test", message: ["value": 3, "another_value": 42]) + + await fulfillment(of: [expectation], timeout: 0.5) + + XCTAssertNoDifference( + receivedMessages.value, + [ + [ + "event": "test", + "payload": [ + "value": 1, + ], + "type": "broadcast", + ], + [ + "event": "test", + "payload": [ + "value": 2, + ], + "type": "broadcast", + ], + [ + "event": "test", + "payload": [ + "value": 3, + "another_value": 42, + ], + "type": "broadcast", + ], + ] + ) + + await channel.unsubscribe() + } + + func testPresence() async throws { + let channel = await realtime.channel("integration") { + $0.broadcast.receiveOwnBroadcasts = true + } + + let expectation = expectation(description: "presenceChange") + expectation.expectedFulfillmentCount = 4 + + let receivedPresenceChanges = LockIsolated<[any PresenceAction]>([]) + + Task { + for await presence in await channel.presenceChange() { + receivedPresenceChanges.withValue { + $0.append(presence) + } + expectation.fulfill() + } + } + + await Task.megaYield() + + await channel.subscribe() + + struct UserState: Codable, Equatable { + let email: String + } + + try await channel.track(UserState(email: "test@supabase.com")) + try await channel.track(["email": "test2@supabase.com"]) + + await channel.untrack() + + await fulfillment(of: [expectation], timeout: 0.5) + + let joins = try receivedPresenceChanges.value.map { try $0.decodeJoins(as: UserState.self) } + let leaves = try receivedPresenceChanges.value.map { try $0.decodeLeaves(as: UserState.self) } + XCTAssertNoDifference( + joins, + [ + [], // This is the first PRESENCE_STATE event. + [UserState(email: "test@supabase.com")], + [UserState(email: "test2@supabase.com")], + [], + ] + ) + + XCTAssertNoDifference( + leaves, + [ + [], // This is the first PRESENCE_STATE event. + [], + [UserState(email: "test@supabase.com")], + [UserState(email: "test2@supabase.com")], + ] + ) + + await channel.unsubscribe() + } + + func testPostgresChanges() async throws { + let channel = await realtime.channel("db-changes") + + let receivedInsertActions = Task { + await channel.postgresChange(InsertAction.self, schema: "public").prefix(1).collect() + } + + let receivedUpdateActions = Task { + await channel.postgresChange(UpdateAction.self, schema: "public").prefix(1).collect() + } + + let receivedDeleteActions = Task { + await channel.postgresChange(DeleteAction.self, schema: "public").prefix(1).collect() + } + + let receivedAnyActionsTask = Task { + await channel.postgresChange(AnyAction.self, schema: "public").prefix(3).collect() + } + + await Task.megaYield() + await channel.subscribe() + + struct Entry: Codable, Equatable { + let key: String + let value: AnyJSON + } + + let key = try await ( + db.from("store") + .insert(["key": AnyJSON.string(UUID().uuidString), "value": "value1"]).select().single() + .execute().value as Entry + ).key + try await db.from("store").update(["value": "value2"]).eq("key", value: key).execute() + try await db.from("store").delete().eq("key", value: key).execute() + + let insertedEntries = try await receivedInsertActions.value.map { try $0.decodeRecord( + as: Entry.self, + decoder: JSONDecoder() + ) } + let updatedEntries = try await receivedUpdateActions.value.map { try $0.decodeRecord( + as: Entry.self, + decoder: JSONDecoder() + ) } + let deletedEntryIds = await receivedDeleteActions.value + .compactMap { $0.oldRecord["key"]?.stringValue } + + XCTAssertNoDifference(insertedEntries, [Entry(key: key, value: "value1")]) + XCTAssertNoDifference(updatedEntries, [Entry(key: key, value: "value2")]) + XCTAssertNoDifference(deletedEntryIds, [key]) + + let receivedAnyActions = await receivedAnyActionsTask.value + XCTAssertEqual(receivedAnyActions.count, 3) + + if case let .insert(action) = receivedAnyActions[0] { + let record = try action.decodeRecord(as: Entry.self, decoder: JSONDecoder()) + XCTAssertNoDifference(record, Entry(key: key, value: "value1")) + } else { + XCTFail("Expected a `AnyAction.insert` on `receivedAnyActions[0]`") + } + + if case let .update(action) = receivedAnyActions[1] { + let record = try action.decodeRecord(as: Entry.self, decoder: JSONDecoder()) + XCTAssertNoDifference(record, Entry(key: key, value: "value2")) + } else { + XCTFail("Expected a `AnyAction.update` on `receivedAnyActions[1]`") + } + + if case let .delete(action) = receivedAnyActions[2] { + XCTAssertNoDifference(key, action.oldRecord["key"]?.stringValue) + } else { + XCTFail("Expected a `AnyAction.delete` on `receivedAnyActions[2]`") + } + + await channel.unsubscribe() + } +} diff --git a/supabase/.gitignore b/supabase/.gitignore new file mode 100644 index 00000000..a3ad8805 --- /dev/null +++ b/supabase/.gitignore @@ -0,0 +1,4 @@ +# Supabase +.branches +.temp +.env diff --git a/supabase/config.toml b/supabase/config.toml new file mode 100644 index 00000000..088ad885 --- /dev/null +++ b/supabase/config.toml @@ -0,0 +1,161 @@ +# A string used to distinguish different Supabase projects on the same host. Defaults to the +# working directory name when running `supabase init`. +project_id = "supabase-swift" + +[api] +enabled = true +# Port to use for the API URL. +port = 54321 +# Schemas to expose in your API. Tables, views and stored procedures in this schema will get API +# endpoints. public and storage are always included. +schemas = ["public", "storage", "graphql_public"] +# Extra schemas to add to the search_path of every request. public is always included. +extra_search_path = ["public", "extensions"] +# The maximum number of rows returns from a view, table, or stored procedure. Limits payload size +# for accidental or malicious requests. +max_rows = 1000 + +[db] +# Port to use for the local database URL. +port = 54322 +# Port used by db diff command to initialize the shadow database. +shadow_port = 54320 +# The database major version to use. This has to be the same as your remote database's. Run `SHOW +# server_version;` on the remote database to check. +major_version = 15 + +[db.pooler] +enabled = false +# Port to use for the local connection pooler. +port = 54329 +# Specifies when a server connection can be reused by other clients. +# Configure one of the supported pooler modes: `transaction`, `session`. +pool_mode = "transaction" +# How many server connections to allow per user/database pair. +default_pool_size = 20 +# Maximum number of client connections allowed. +max_client_conn = 100 + +[realtime] +enabled = true +# Bind realtime via either IPv4 or IPv6. (default: IPv6) +# ip_version = "IPv6" +# The maximum length in bytes of HTTP request headers. (default: 4096) +# max_header_length = 4096 + +[studio] +enabled = true +# Port to use for Supabase Studio. +port = 54323 +# External URL of the API server that frontend connects to. +api_url = "http://127.0.0.1" +# OpenAI API Key to use for Supabase AI in the Supabase Studio. +openai_api_key = "env(OPENAI_API_KEY)" + +# Email testing server. Emails sent with the local dev setup are not actually sent - rather, they +# are monitored, and you can view the emails that would have been sent from the web interface. +[inbucket] +enabled = true +# Port to use for the email testing server web interface. +port = 54324 +# Uncomment to expose additional ports for testing user applications that send emails. +# smtp_port = 54325 +# pop3_port = 54326 + +[storage] +enabled = true +# The maximum file size allowed (e.g. "5MB", "500KB"). +file_size_limit = "50MiB" + +[auth] +enabled = true +# The base URL of your website. Used as an allow-list for redirects and for constructing URLs used +# in emails. +site_url = "http://127.0.0.1:3000" +# A list of *exact* URLs that auth providers are permitted to redirect to post authentication. +additional_redirect_urls = ["https://127.0.0.1:3000"] +# How long tokens are valid for, in seconds. Defaults to 3600 (1 hour), maximum 604,800 (1 week). +jwt_expiry = 3600 +# If disabled, the refresh token will never expire. +enable_refresh_token_rotation = true +# Allows refresh tokens to be reused after expiry, up to the specified interval in seconds. +# Requires enable_refresh_token_rotation = true. +refresh_token_reuse_interval = 10 +# Allow/disallow new user signups to your project. +enable_signup = true +# Allow/disallow testing manual linking of accounts +enable_manual_linking = true + +[auth.email] +# Allow/disallow new user signups via email to your project. +enable_signup = true +# If enabled, a user will be required to confirm any email change on both the old, and new email +# addresses. If disabled, only the new email is required to confirm. +double_confirm_changes = true +# If enabled, users need to confirm their email address before signing in. +enable_confirmations = false + +# Uncomment to customize email template +# [auth.email.template.invite] +# subject = "You have been invited" +# content_path = "./supabase/templates/invite.html" + +[auth.sms] +# Allow/disallow new user signups via SMS to your project. +enable_signup = true +# If enabled, users need to confirm their phone number before signing in. +enable_confirmations = false +# Template for sending OTP to users +template = "Your code is {{ .Code }} ." + +# Use pre-defined map of phone number to OTP for testing. +[auth.sms.test_otp] +4152127777 = "123456" + +# This hook runs before a token is issued and allows you to add additional claims based on the authentication method used. +[auth.hook.custom_access_token] +# enabled = true +# uri = "pg-functions:////" + + +# Configure one of the supported SMS providers: `twilio`, `twilio_verify`, `messagebird`, `textlocal`, `vonage`. +[auth.sms.twilio] +enabled = false +account_sid = "" +message_service_sid = "" +# DO NOT commit your Twilio auth token to git. Use environment variable substitution instead: +auth_token = "env(SUPABASE_AUTH_SMS_TWILIO_AUTH_TOKEN)" + +# Use an external OAuth provider. The full list of providers are: `apple`, `azure`, `bitbucket`, +# `discord`, `facebook`, `github`, `gitlab`, `google`, `keycloak`, `linkedin_oidc`, `notion`, `twitch`, +# `twitter`, `slack`, `spotify`, `workos`, `zoom`. +[auth.external.apple] +enabled = false +client_id = "" +# DO NOT commit your OAuth provider secret to git. Use environment variable substitution instead: +secret = "env(SUPABASE_AUTH_EXTERNAL_APPLE_SECRET)" +# Overrides the default auth redirectUrl. +redirect_uri = "" +# Overrides the default auth provider URL. Used to support self-hosted gitlab, single-tenant Azure, +# or any other third-party OIDC providers. +url = "" + +[analytics] +enabled = false +port = 54327 +vector_port = 54328 +# Configure one of the supported backends: `postgres`, `bigquery`. +backend = "postgres" + +# Experimental features may be deprecated any time +[experimental] +# Configures Postgres storage engine to use OrioleDB (S3) +orioledb_version = "" +# Configures S3 bucket URL, eg. .s3-.amazonaws.com +s3_host = "env(S3_HOST)" +# Configures S3 bucket region, eg. us-east-1 +s3_region = "env(S3_REGION)" +# Configures AWS_ACCESS_KEY_ID for S3 bucket +s3_access_key = "env(S3_ACCESS_KEY)" +# Configures AWS_SECRET_ACCESS_KEY for S3 bucket +s3_secret_key = "env(S3_SECRET_KEY)" diff --git a/supabase/migrations/20240327182636_init_store_schema.sql b/supabase/migrations/20240327182636_init_store_schema.sql new file mode 100644 index 00000000..e8e239c6 --- /dev/null +++ b/supabase/migrations/20240327182636_init_store_schema.sql @@ -0,0 +1,8 @@ +create table store( + "key" text primary key, + "value" jsonb not null +); + +alter publication supabase_realtime + add table store; + diff --git a/supabase/seed.sql b/supabase/seed.sql new file mode 100644 index 00000000..e69de29b