|
| 1 | +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. |
| 2 | +// SPDX-License-Identifier: Apache-2.0 |
| 3 | + |
| 4 | +import 'package:amplify_firehose_dart/src/exception/amplify_firehose_exception.dart' |
| 5 | + show defaultRecoverySuggestion; |
| 6 | +import 'package:amplify_firehose_dart/src/exception/record_cache_exception.dart'; |
| 7 | +import 'package:amplify_firehose_dart/src/firehose_limits.dart' as limits; |
| 8 | +import 'package:amplify_firehose_dart/src/impl/firehose_record.dart'; |
| 9 | +import 'package:amplify_firehose_dart/src/model/record.dart'; |
| 10 | +import 'package:meta/meta.dart'; |
| 11 | + |
| 12 | +export 'package:amplify_firehose_dart/src/model/record.dart'; |
| 13 | + |
| 14 | +/// {@template amplify_firehose.record_storage} |
| 15 | +/// Abstract base class for record persistence. |
| 16 | +/// |
| 17 | +/// Implementations provide platform-specific storage (SQLite on VM, |
| 18 | +/// IndexedDB on web, in-memory fallback). Validation of record size |
| 19 | +/// and cache limits is handled here in [addRecord]; subclasses |
| 20 | +/// implement [writeRecord] for the actual write. |
| 21 | +/// |
| 22 | +/// All public methods wrap unexpected errors as |
| 23 | +/// [RecordCacheDatabaseException]. Subclasses throw |
| 24 | +/// [RecordCacheException] subtypes for known errors; anything else is |
| 25 | +/// caught and wrapped automatically. |
| 26 | +/// {@endtemplate} |
| 27 | +abstract class RecordStorage { |
| 28 | + /// {@macro amplify_firehose.record_storage} |
| 29 | + RecordStorage({ |
| 30 | + required int maxCacheBytes, |
| 31 | + int maxRecordsPerBatch = limits.maxRecordsPerBatch, |
| 32 | + int maxBytesPerBatch = limits.maxBatchSizeBytes, |
| 33 | + int maxRecordSizeBytes = limits.maxRecordSizeBytes, |
| 34 | + int initialCachedSize = 0, |
| 35 | + }) : _maxCacheBytes = maxCacheBytes, |
| 36 | + _maxRecordsPerBatch = maxRecordsPerBatch, |
| 37 | + _maxBytesPerBatch = maxBytesPerBatch, |
| 38 | + _maxRecordSizeBytes = maxRecordSizeBytes, |
| 39 | + cachedSize = initialCachedSize; |
| 40 | + |
| 41 | + final int _maxCacheBytes; |
| 42 | + final int _maxRecordsPerBatch; |
| 43 | + final int _maxBytesPerBatch; |
| 44 | + final int _maxRecordSizeBytes; |
| 45 | + |
| 46 | + /// The current total cached size in bytes. |
| 47 | + @protected |
| 48 | + int cachedSize; |
| 49 | + |
| 50 | + /// The maximum cache size in bytes. |
| 51 | + int get maxCacheBytes => _maxCacheBytes; |
| 52 | + |
| 53 | + /// Maximum number of records per batch. |
| 54 | + int get maxRecordsPerBatch => _maxRecordsPerBatch; |
| 55 | + |
| 56 | + /// Maximum total bytes per batch. |
| 57 | + int get maxBytesPerBatch => _maxBytesPerBatch; |
| 58 | + |
| 59 | + /// Validates and saves a record to storage. |
| 60 | + /// Throws [RecordCacheValidationException] on invalid input. |
| 61 | + /// Throws [RecordCacheLimitExceededException] if the cache is full. |
| 62 | + /// Throws [RecordCacheDatabaseException] on storage errors. |
| 63 | + Future<void> addRecord(RecordInput record) => |
| 64 | + _wrap('Failed to add record to cache', () async { |
| 65 | + if (record.dataSize > _maxRecordSizeBytes) { |
| 66 | + throw RecordCacheValidationException( |
| 67 | + 'Record size (${record.dataSize} bytes) exceeds the maximum ' |
| 68 | + 'of $_maxRecordSizeBytes bytes.', |
| 69 | + 'Reduce the record payload size.', |
| 70 | + ); |
| 71 | + } |
| 72 | + if (cachedSize + record.dataSize > _maxCacheBytes) { |
| 73 | + throw RecordCacheLimitExceededException( |
| 74 | + 'Cache size limit exceeded: ' |
| 75 | + '${cachedSize + record.dataSize} bytes > $_maxCacheBytes bytes', |
| 76 | + 'Call flush() to send cached records or increase cache size limit.', |
| 77 | + ); |
| 78 | + } |
| 79 | + await writeRecord(record); |
| 80 | + cachedSize += record.dataSize; |
| 81 | + }); |
| 82 | + |
| 83 | + /// Retrieves records grouped by stream. |
| 84 | + Future<Map<String, List<Record>>> getRecordsByStream() => |
| 85 | + _wrap('Could not retrieve records from storage', doGetRecordsByStream); |
| 86 | + |
| 87 | + /// Deletes records by their IDs and refreshes [cachedSize]. |
| 88 | + Future<void> deleteRecords(Iterable<int> ids) => |
| 89 | + _wrap('Failed to delete records from cache', () async { |
| 90 | + await doDeleteRecords(ids); |
| 91 | + cachedSize = await doQueryCacheSize(); |
| 92 | + }); |
| 93 | + |
| 94 | + /// Increments the retry count for the specified records. |
| 95 | + Future<void> incrementRetryCount(Iterable<int> ids) => _wrap( |
| 96 | + 'Failed to increment retry count', |
| 97 | + () => doIncrementRetryCount(ids), |
| 98 | + ); |
| 99 | + |
| 100 | + /// Returns the total number of cached records. |
| 101 | + Future<int> getRecordCount() => |
| 102 | + _wrap('Failed to get record count', doGetRecordCount); |
| 103 | + |
| 104 | + /// Deletes all records and resets [cachedSize] to 0. |
| 105 | + Future<void> clearRecords() => _wrap('Failed to clear cache', () async { |
| 106 | + await doClearRecords(); |
| 107 | + cachedSize = 0; |
| 108 | + }); |
| 109 | + |
| 110 | + /// Closes the storage and releases resources. |
| 111 | + Future<void> close() => _wrap('Failed to close storage', doClose); |
| 112 | + |
| 113 | + /// Writes a validated record to the underlying storage. |
| 114 | + @protected |
| 115 | + Future<void> writeRecord(RecordInput record); |
| 116 | + |
| 117 | + /// Retrieves records grouped by stream name. |
| 118 | + @protected |
| 119 | + Future<Map<String, List<Record>>> doGetRecordsByStream(); |
| 120 | + |
| 121 | + /// Deletes records by their IDs. |
| 122 | + @protected |
| 123 | + Future<void> doDeleteRecords(Iterable<int> ids); |
| 124 | + |
| 125 | + /// Increments the retry count for the specified records. |
| 126 | + @protected |
| 127 | + Future<void> doIncrementRetryCount(Iterable<int> ids); |
| 128 | + |
| 129 | + /// Returns the total number of cached records. |
| 130 | + @protected |
| 131 | + Future<int> doGetRecordCount(); |
| 132 | + |
| 133 | + /// Deletes all records (without updating [cachedSize] — the base class |
| 134 | + /// resets it to 0). |
| 135 | + @protected |
| 136 | + Future<void> doClearRecords(); |
| 137 | + |
| 138 | + /// Returns the current total cache size in bytes from the underlying |
| 139 | + /// storage. Called by the base class after deletions. |
| 140 | + @protected |
| 141 | + Future<int> doQueryCacheSize(); |
| 142 | + |
| 143 | + /// Closes the storage and releases resources. |
| 144 | + @protected |
| 145 | + Future<void> doClose(); |
| 146 | + |
| 147 | + Future<T> _wrap<T>(String message, Future<T> Function() operation) async { |
| 148 | + try { |
| 149 | + return await operation(); |
| 150 | + } on RecordCacheException { |
| 151 | + rethrow; |
| 152 | + } on Object catch (e) { |
| 153 | + throw RecordCacheDatabaseException(message, defaultRecoverySuggestion, e); |
| 154 | + } |
| 155 | + } |
| 156 | +} |
0 commit comments