-
Notifications
You must be signed in to change notification settings - Fork 29
[Fix] CRUD Upload on Reconnect #203
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 7 commits
Commits
Show all changes
16 commits
Select commit
Hold shift + click to select a range
a427124
trigger crud upload on reconnect
stevensJourney ce5d99a
wip: mock server
stevensJourney 0267e98
add native tests
stevensJourney b07b034
skip web test
stevensJourney 4df902c
cleanup
stevensJourney ed582bb
cleanup
stevensJourney dd32fdf
more cleanup
stevensJourney 5e35907
remove comment
stevensJourney fa49b64
Update packages/powersync/test/streaming_sync_test.dart
stevensJourney bf8cd83
lint fixes. Use inhouse mergeStreams
stevensJourney f42b9a8
fix tests
stevensJourney 0d557cb
automatic teardown of server
stevensJourney b771349
use test name in logs for better readability
stevensJourney 6a4e650
exit crud loop on disconnect faster
stevensJourney 3339926
code cleanup
stevensJourney c92e7f5
chore(release): publish packages
stevensJourney File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,128 @@ | ||
@TestOn('!browser') | ||
// This test uses a local server which is possible to control in Web via hybrid main, | ||
// but this makes the test significantly more complex. | ||
import 'dart:async'; | ||
|
||
import 'package:powersync/powersync.dart'; | ||
import 'package:test/test.dart'; | ||
|
||
import 'server/sync_server/mock_sync_server.dart'; | ||
import 'streaming_sync_test.dart'; | ||
import 'utils/abstract_test_utils.dart'; | ||
import 'utils/test_utils_impl.dart'; | ||
|
||
final testUtils = TestUtils(); | ||
|
||
void main() { | ||
late TestHttpServerHelper testServer; | ||
late String path; | ||
|
||
setUp(() async { | ||
path = testUtils.dbPath(); | ||
testServer = TestHttpServerHelper(); | ||
await testServer.start(); | ||
}); | ||
|
||
tearDown(() async { | ||
await testUtils.cleanDb(path: path); | ||
await testServer.stop(); | ||
}); | ||
|
||
test('should connect to mock PowerSync instance', () async { | ||
final connector = TestConnector(() async { | ||
return PowerSyncCredentials( | ||
endpoint: testServer.uri.toString(), | ||
token: 'token not used here', | ||
expiresAt: DateTime.now()); | ||
}); | ||
|
||
final db = PowerSyncDatabase.withFactory( | ||
await testUtils.testFactory(path: path), | ||
schema: defaultSchema, | ||
maxReaders: 3); | ||
await db.initialize(); | ||
|
||
final connectedCompleter = Completer(); | ||
|
||
db.statusStream.listen((status) { | ||
if (status.connected) { | ||
connectedCompleter.complete(); | ||
} | ||
}); | ||
|
||
// Add a basic command for the test server to send | ||
testServer.addEvent('{"token_expires_in": 3600}\n'); | ||
|
||
await db.connect(connector: connector); | ||
await connectedCompleter.future; | ||
|
||
expect(db.connected, isTrue); | ||
}); | ||
|
||
test('should trigger uploads when connection is re-established', () async { | ||
int uploadCounter = 0; | ||
Completer uploadTriggeredCompleter = Completer(); | ||
|
||
final connector = TestConnector(() async { | ||
return PowerSyncCredentials( | ||
endpoint: testServer.uri.toString(), | ||
token: 'token not used here', | ||
expiresAt: DateTime.now()); | ||
}, uploadData: (database) async { | ||
uploadCounter++; | ||
uploadTriggeredCompleter.complete(); | ||
throw Exception('No uploads occur here'); | ||
}); | ||
|
||
final db = PowerSyncDatabase.withFactory( | ||
await testUtils.testFactory(path: path), | ||
schema: defaultSchema, | ||
maxReaders: 3); | ||
await db.initialize(); | ||
|
||
// Create an item which should trigger an upload. | ||
await db.execute( | ||
'INSERT INTO customers (id, name) VALUES (uuid(), ?)', ['steven']); | ||
|
||
// Create a new completer to await the next upload | ||
uploadTriggeredCompleter = Completer(); | ||
|
||
// Connect the PowerSync instance | ||
final connectedCompleter = Completer(); | ||
// The first connection attempt will fail | ||
final connectedErroredCompleter = Completer(); | ||
|
||
db.statusStream.listen((status) { | ||
if (status.connected) { | ||
connectedCompleter.complete(); | ||
} | ||
if (status.downloadError != null && | ||
!connectedErroredCompleter.isCompleted) { | ||
connectedErroredCompleter.complete(); | ||
} | ||
}); | ||
|
||
// The first command will not be valid, this simulates a failed connection | ||
testServer.addEvent('asdf\n'); | ||
await db.connect(connector: connector); | ||
|
||
// The connect operation should have triggered an upload (even though it fails to connect) | ||
await uploadTriggeredCompleter.future; | ||
expect(uploadCounter, equals(1)); | ||
// Create a new completer for the next iteration | ||
uploadTriggeredCompleter = Completer(); | ||
|
||
// Connection attempt should initially fail | ||
await connectedErroredCompleter.future; | ||
expect(db.currentStatus.anyError, isNotNull); | ||
|
||
// Now send a valid command. Which will result in successful connection | ||
await testServer.clearEvents(); | ||
testServer.addEvent('{"token_expires_in": 3600}\n'); | ||
await connectedCompleter.future; | ||
expect(db.connected, isTrue); | ||
|
||
await uploadTriggeredCompleter.future; | ||
expect(uploadCounter, equals(2)); | ||
}); | ||
} |
54 changes: 54 additions & 0 deletions
54
packages/powersync/test/server/sync_server/mock_sync_server.dart
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,54 @@ | ||
import 'dart:async'; | ||
import 'dart:convert'; | ||
import 'dart:io'; | ||
|
||
import 'package:shelf/shelf.dart'; | ||
import 'package:shelf/shelf_io.dart' as io; | ||
import 'package:shelf_router/shelf_router.dart'; | ||
|
||
// A basic Mock PowerSync service server which queues commands | ||
// which clients can receive via connecting to the `/sync/stream` route. | ||
// This assumes only one client will ever be connected at a time. | ||
class TestHttpServerHelper { | ||
// Use a queued stream to make tests easier. | ||
StreamController<String> _controller = StreamController<String>(); | ||
late HttpServer _server; | ||
Uri get uri => Uri.parse('http://localhost:${_server.port}'); | ||
|
||
Future<void> start() async { | ||
final router = Router() | ||
..post('/sync/stream', (Request request) async { | ||
// Respond immediately with a stream | ||
return Response.ok(_controller.stream.transform(utf8.encoder), | ||
headers: { | ||
'Content-Type': 'text/event-stream', | ||
'Cache-Control': 'no-cache', | ||
'Connection': 'keep-alive', | ||
'Transfer-Encoding': 'identity', // Use chunked transfer encoding | ||
}, | ||
context: { | ||
"shelf.io.buffer_output": false | ||
}); | ||
}); | ||
|
||
_server = await io.serve(router, 'localhost', 0); | ||
print('Test server running at ${_server.address}:${_server.port}'); | ||
} | ||
|
||
// Queue events which will be sent to connected clients. | ||
void addEvent(String data) { | ||
_controller.add(data); | ||
} | ||
|
||
// Clear events. We rely on a buffered controller here. Create a new controller | ||
// in order to clear the buffer. | ||
Future<void> clearEvents() async { | ||
await _controller.close(); | ||
_controller = StreamController<String>(); | ||
} | ||
|
||
Future<void> stop() async { | ||
await _controller.close(); | ||
await _server.close(); | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.