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
13 changes: 13 additions & 0 deletions packages/syncache_hive/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
## 0.1.0

- Initial release
- `HiveStore<T>` implementation of `TaggableStore<T>`
- Full support for tag-based cache invalidation
- Pattern-based key matching and deletion
- Automatic JSON serialization for metadata
- Atomic operations - tags embedded in entries for consistency
- State management with `isOpen`/`isClosed` properties
- Graceful handling of corrupted data (returns null, deletes entry)
- Idempotent `close()` method
- Thread-safe `close()` - waits for pending operations to complete
- Graceful handling of invalid tags data (returns empty list)
21 changes: 21 additions & 0 deletions packages/syncache_hive/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2026 Hameed Abdullateef

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
175 changes: 175 additions & 0 deletions packages/syncache_hive/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,175 @@
# syncache_hive

Hive storage backend for [Syncache](https://pub.dev/packages/syncache) - cross-platform persistent caching.

## Features

- Persistent storage using [Hive](https://pub.dev/packages/hive)
- Cross-platform support (iOS, Android, Web, Desktop, Pure Dart)
- Full support for tag-based cache invalidation
- Pattern-based key matching and deletion
- Automatic serialization via JSON
- **Atomic operations** - each entry (data + tags) is stored as a single unit

## Installation

Add `syncache_hive` to your `pubspec.yaml`:

```yaml
dependencies:
syncache: ^0.1.0
syncache_hive: ^0.1.0
hive: ^2.2.0
```

For Flutter apps, also add `hive_flutter`:

```yaml
dependencies:
hive_flutter: ^1.1.0
```

## Usage

### Basic Setup

```dart
import 'package:hive/hive.dart';
import 'package:syncache/syncache.dart';
import 'package:syncache_hive/syncache_hive.dart';

void main() async {
// Initialize Hive (required once per app)
Hive.init('path/to/hive');

// Open a HiveStore with your data type
final store = await HiveStore.open<User>(
boxName: 'users',
fromJson: User.fromJson,
toJson: (user) => user.toJson(),
);

// Create a Syncache instance with the store
final cache = Syncache<User>(store: store);

// Use the cache
final user = await cache.get(
key: 'user:123',
fetch: (req) => api.getUser('123'),
);
}
```

### Flutter Setup

```dart
import 'package:flutter/material.dart';
import 'package:hive_flutter/hive_flutter.dart';
import 'package:syncache/syncache.dart';
import 'package:syncache_hive/syncache_hive.dart';

void main() async {
WidgetsFlutterBinding.ensureInitialized();

// Initialize Hive for Flutter
await Hive.initFlutter();

final store = await HiveStore.open<User>(
boxName: 'users',
fromJson: User.fromJson,
toJson: (user) => user.toJson(),
);

final cache = Syncache<User>(store: store);

runApp(MyApp(cache: cache));
}
```

### Using Tags

```dart
// Store with tags for grouped invalidation
await cache.get(
key: 'calendar:events:2024-03',
fetch: fetchEvents,
tags: ['calendar', 'events', 'workspace:123'],
);

// Invalidate all entries with 'calendar' tag
await cache.invalidateTag('calendar');
```

### Closing the Store

Remember to close the store when you're done:

```dart
await store.close();
```

## API Reference

### HiveStore

```dart
class HiveStore<T> implements TaggableStore<T> {
/// Opens a HiveStore with the specified box name.
static Future<HiveStore<T>> open<T>({
required String boxName,
required T Function(Map<String, dynamic>) fromJson,
required Map<String, dynamic> Function(T) toJson,
});

/// Closes the store and releases resources.
Future<void> close();
}
```

### Inherited from TaggableStore

- `write(key, entry)` - Store a value
- `writeWithTags(key, entry, tags)` - Store a value with tags
- `read(key)` - Retrieve a value
- `delete(key)` - Delete a value
- `clear()` - Clear all values
- `getTags(key)` - Get tags for a key
- `getKeysByTag(tag)` - Get all keys with a tag
- `deleteByTag(tag)` - Delete all entries with a tag
- `deleteByTags(tags, {matchAll})` - Delete entries matching tags
- `getKeysByPattern(pattern)` - Get keys matching a glob pattern
- `deleteByPattern(pattern)` - Delete keys matching a glob pattern

## Limitations

- **Key length**: Hive limits keys to a maximum of 255 characters. Attempting to use longer keys will throw a `HiveError`.
- **Tag replacement**: Unlike `MemoryStore`, calling `write()` on a key that already has tags will remove those tags. Use `writeWithTags()` to explicitly set tags.

## Serialization

HiveStore requires `fromJson` and `toJson` functions to serialize your data type. This is because Hive stores data as maps internally.

```dart
class User {
final String name;
final String email;

User({required this.name, required this.email});

factory User.fromJson(Map<String, dynamic> json) {
return User(
name: json['name'] as String,
email: json['email'] as String,
);
}

Map<String, dynamic> toJson() => {
'name': name,
'email': email,
};
}
```

## License

MIT License - see LICENSE file for details.
10 changes: 10 additions & 0 deletions packages/syncache_hive/analysis_options.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
include: package:lints/recommended.yaml

linter:
rules:
- prefer_const_constructors
- prefer_const_declarations
- prefer_final_fields
- prefer_final_locals
- avoid_print
- require_trailing_commas
129 changes: 129 additions & 0 deletions packages/syncache_hive/example/syncache_hive_example.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,129 @@
// ignore_for_file: unused_local_variable, avoid_print

import 'dart:io';

import 'package:hive/hive.dart';
import 'package:syncache/syncache.dart';
import 'package:syncache_hive/syncache_hive.dart';

/// Example model with JSON serialization.
class User {
final String id;
final String name;
final String email;

User({required this.id, required this.name, required this.email});

factory User.fromJson(Map<String, dynamic> json) {
return User(
id: json['id'] as String,
name: json['name'] as String,
email: json['email'] as String,
);
}

Map<String, dynamic> toJson() => {
'id': id,
'name': name,
'email': email,
};

@override
String toString() => 'User($id, $name, $email)';
}

Future<void> main() async {
// Initialize Hive with a directory path
final tempDir = await Directory.systemTemp.createTemp('hive_example_');
Hive.init(tempDir.path);

// Open a HiveStore with JSON serialization functions
final store = await HiveStore.open<User>(
boxName: 'users',
fromJson: User.fromJson,
toJson: (user) => user.toJson(),
);

// Create a Syncache instance with the persistent store
final cache = Syncache<User>(store: store);

// --- Basic Usage ---

// Fetch and cache a user
final user = await cache.get(
key: 'user:1',
fetch: (req) async {
// Simulate API call
return User(id: '1', name: 'Alice', email: 'alice@example.com');
},
);
print('Fetched: $user');

// Subsequent calls return cached value (no fetch)
final cachedUser = await cache.get(
key: 'user:1',
fetch: (req) async {
throw StateError('Should not be called - using cache');
},
);
print('Cached: $cachedUser');

// --- Using Tags ---

// Store users with tags for grouped invalidation
await cache.get(
key: 'user:2',
fetch: (req) async => User(id: '2', name: 'Bob', email: 'bob@example.com'),
tags: ['team:engineering', 'role:developer'],
);

await cache.get(
key: 'user:3',
fetch: (req) async =>
User(id: '3', name: 'Carol', email: 'carol@example.com'),
tags: ['team:engineering', 'role:manager'],
);

// Invalidate all entries with a specific tag
await cache.invalidateTag('team:engineering');
print('Invalidated all engineering team members');

// --- Pattern-Based Operations ---

// Store multiple items
await cache.get(
key: 'user:active:4',
fetch: (req) async =>
User(id: '4', name: 'Dave', email: 'dave@example.com'),
);

await cache.get(
key: 'user:active:5',
fetch: (req) async => User(id: '5', name: 'Eve', email: 'eve@example.com'),
);

// Invalidate by pattern (glob-style wildcards)
await cache.invalidate('user:active:*');
print('Invalidated all active users');

// --- Direct Store Operations ---

// Get keys matching a pattern
final keys = await store.getKeysByPattern('user:*');
print('Keys matching "user:*": $keys');

// Get tags for a specific key
final tags = await store.getTags('user:1');
print('Tags for user:1: $tags');

// --- Cleanup ---

// Dispose cache and close store
cache.dispose();
await store.close();

// Clean up temp directory
await tempDir.delete(recursive: true);

print('Done!');
}
Loading
Loading