Skip to content

Commit 7dd4f0f

Browse files
committed
docs: optimize CosId skills
1 parent b3e5c09 commit 7dd4f0f

9 files changed

Lines changed: 217 additions & 102 deletions

File tree

skills/cosid-manual-integration/SKILL.md

Lines changed: 57 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,21 @@
11
---
22
name: cosid-manual-integration
3-
description: Guide for manually integrating CosId into Java/Kotlin projects without Spring Boot auto-configuration. Use this skill when the user wants to configure CosId programmatically, set up custom ID generators, integrate CosId in non-Spring environments, asks about CosId core API usage (SnowflakeId, SegmentId, CosIdGenerator), needs to configure machine ID allocation manually, or mentions "manual integration", "programmatic configuration", "without Spring Boot", "non-Spring environment", or "library integration".
3+
description: Manually integrate CosId into Java or Kotlin applications without Spring Boot auto-configuration. Use when the user needs programmatic setup for SnowflakeId, SegmentId, SegmentChainId, CosIdGenerator, machine ID distribution, custom IdConverter wiring, non-Spring environments, library/framework integration, or production-safe generator lifecycle management.
44
---
55

66
# CosId Manual Integration Skill
77

8-
## Instructions
8+
Use this skill when CosId must be configured with code instead of `cosid-spring-boot-starter`.
99

10-
### When to Use
10+
## Workflow
1111

12-
- User wants to integrate CosId without Spring Boot
13-
- User needs custom programmatic configuration of ID generators
14-
- User is building a library or framework that needs ID generation
15-
- User asks about CosId core API usage (SnowflakeId, SegmentId, CosIdGenerator)
16-
- User needs to configure machine ID allocation manually
12+
1. Identify the generator strategy. Use `$cosid-strategy-guide` first if the user has not chosen one.
13+
2. Identify the coordination mechanism: manual machine ID, StatefulSet ordinal, Redis, JDBC, MongoDB, ZooKeeper, or proxy.
14+
3. Show the minimal constructor/wiring path for the chosen generator.
15+
4. Include lifecycle handling for distributors, guard/heartbeat, prefetch workers, and state storage when relevant.
16+
5. Add a small verification example: uniqueness, monotonicity, parser behavior, or restart behavior.
1717

18-
### Core Architecture
18+
## Core APIs
1919

2020
CosId provides three main ID generation strategies:
2121

@@ -33,22 +33,24 @@ CosId provides three main ID generation strategies:
3333
- Requires `MachineIdDistributor` for machine ID allocation (same as SnowflakeId)
3434
- Supports much larger instance counts than SnowflakeId (not constrained by 63-bit long format)
3535

36-
### Machine ID Allocation
36+
## Machine ID Allocation
3737

3838
For SnowflakeId, each instance needs a unique machineId. Options:
3939

4040
- **Manual**: Set machineId directly (0-1023 for default 10-bit)
41-
- **Redis**: `RedisMachineIdDistributor` - uses Redis for coordination
41+
- **Redis**: `SpringRedisMachineIdDistributor` - uses Redis for coordination
4242
- **JDBC**: `JdbcMachineIdDistributor` - uses database table
4343
- **ZooKeeper**: `ZookeeperMachineIdDistributor` - uses ZK nodes
4444
- **MongoDB**: `MongoMachineIdDistributor` - uses MongoDB collection
4545
- **StatefulSet**: Kubernetes StatefulSet ordinal as machineId
4646

47-
### Manual Configuration Pattern
47+
Always define the namespace and instance identity deliberately. For production, prefer a distributor that can guard ownership and reclaim expired machine IDs.
48+
49+
## SnowflakeId Configuration Pattern
4850

4951
```java
50-
// 1. Create machine ID distributor
51-
MachineIdDistributor distributor = new RedisMachineIdDistributor(redisTemplate);
52+
// 1. Create a backend-specific MachineIdDistributor
53+
MachineIdDistributor distributor = createMachineIdDistributor();
5254

5355
// 2. Allocate machine ID
5456
int machineId = distributor.distribute("my-namespace", instanceId, Duration.ofSeconds(10));
@@ -63,7 +65,34 @@ SnowflakeId safeId = new ClockSyncSnowflakeId(snowflakeId);
6365
long id = safeId.generate();
6466
```
6567

66-
### Key Configuration Parameters
68+
If the user has fixed deployment slots, use `ManualMachineIdDistributor` or directly provide the machine ID, but warn that duplicate machine IDs can create duplicate IDs.
69+
70+
## Segment Configuration Pattern
71+
72+
Use `SegmentId` or `SegmentChainId` when monotonic IDs and batch allocation are more important than time-encoded IDs.
73+
74+
```java
75+
IdSegmentDistributor distributor = createIdSegmentDistributor("order_id", 100);
76+
SegmentChainId idGenerator = new SegmentChainId(distributor);
77+
78+
long id = idGenerator.generate();
79+
String text = idGenerator.generateAsString();
80+
```
81+
82+
For `SegmentChainId`, ensure the prefetch worker lifecycle is owned by the application and is closed during shutdown if the concrete setup exposes close/shutdown behavior.
83+
84+
## CosIdGenerator Pattern
85+
86+
Use `CosIdGenerator` when callers need compact string IDs rather than `long` IDs.
87+
88+
```java
89+
CosIdGenerator generator = new Radix62CosIdGenerator(machineId);
90+
String id = generator.generateAsString();
91+
```
92+
93+
Wrap with the clock-sync variant when system clock drift is a production concern.
94+
95+
## Key Parameters
6796

6897
| Parameter | Default | Description |
6998
|-----------|---------|-------------|
@@ -73,22 +102,32 @@ long id = safeId.generate();
73102
| sequenceBit | 12 (ms) / 22 (s) | IDs per time unit per machine |
74103
| clockSync | true | Enable clock backwards synchronization |
75104

76-
### Common Pitfalls
105+
## Common Pitfalls
77106

78107
- **Clock backwards**: Always use `ClockSyncSnowflakeId` wrapper in production
79108
- **Machine ID overflow**: With 10 bits, max 1024 instances per namespace
80109
- **Sequence exhaustion**: High throughput may need `SecondSnowflakeId` (4M/s/machine) over millisecond variant (4K/s/machine)
81110
- **JavaScript safety**: Use `SafeJavaScriptSnowflakeId` if IDs go to frontend
111+
- **Lifecycle leaks**: Close distributor clients and background workers when the application shuts down
112+
- **State loss**: Persist machine state when restart stability matters
82113

83-
### Testing Configuration
114+
## Testing Configuration
84115

85116
For tests, use `ManualMachineIdDistributor` with fixed machine IDs:
86117

87118
```java
88119
MachineIdDistributor distributor = new ManualMachineIdDistributor(1);
89120
```
90121

91-
## References
122+
Add tests for the property that matters in the user's case:
123+
124+
- Uniqueness across concurrent generation
125+
- Local monotonicity for SegmentId/SegmentChainId
126+
- Time parser correctness for SnowflakeId
127+
- JavaScript-safe range or string conversion
128+
- Machine ID conflict behavior when manual IDs are used
129+
130+
## Source Pointers
92131

93132
- Source: `cosid-core/src/main/java/me/ahoo/cosid/`
94133
- Examples: `examples/` directory
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
interface:
2+
display_name: "CosId Manual Integration"
3+
short_description: "Integrate CosId without Spring Boot"
4+
default_prompt: "Use $cosid-manual-integration to wire CosId programmatically without Spring Boot."

skills/cosid-sharding/SKILL.md

Lines changed: 35 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,19 @@
11
---
22
name: cosid-sharding
3-
description: Guide for using CosId sharding algorithms for database sharding with ShardingSphere. Use this skill whenever the user mentions database sharding, table sharding, ShardingSphere, interval sharding, modulo sharding, date-based sharding, range sharding, or needs to distribute data across multiple database tables or nodes. Also use when the user asks about ModCycle, IntervalTimeline, CachedSharding, PreciseSharding, RangeSharding, or SnowflakeLocalDateTimeConvertor.
3+
description: Design and configure CosId sharding algorithms for database sharding and ShardingSphere. Use when the user mentions table or database sharding, ShardingSphere COSID_MOD or COSID_INTERVAL rules, modulo sharding, date/time interval sharding, range routing, SnowflakeId timestamp extraction, ModCycle, IntervalTimeline, CachedSharding, PreciseSharding, RangeSharding, or SnowflakeLocalDateTimeConvertor.
44
---
55

66
# CosId Sharding Algorithms
77

8-
CosId provides sharding algorithms designed for database sharding, compatible with Apache ShardingSphere. All algorithms implement both precise sharding (single key lookup) and range sharding (key range lookup).
8+
Use this skill to choose, configure, and validate CosId sharding behavior.
9+
10+
## Workflow
11+
12+
1. Identify the sharding key type: numeric ID, SnowflakeId, `LocalDateTime`, or an existing timestamp column.
13+
2. Choose the algorithm: `ModCycle` for uniform numeric distribution, `IntervalTimeline` for time ranges, or `CachedSharding` to cache repeated range routing.
14+
3. Confirm both precise and range queries. ShardingSphere routes `=`, `IN`, and range predicates differently.
15+
4. Define effective nodes and bounds explicitly. For interval sharding, include lower/upper datetime bounds and suffix format.
16+
5. Provide a minimal Java or ShardingSphere YAML example and a routing test.
917

1018
## Sharding Algorithm Types
1119

@@ -34,6 +42,8 @@ Implementations:
3442

3543
Distributes numeric IDs across nodes using `value % divisor`. Best for uniform distribution when using SnowflakeId or SegmentId.
3644

45+
Use `ModCycle` when the sharding key is already numeric and the desired distribution is even across a fixed number of tables or databases.
46+
3747
### Usage
3848

3949
```java
@@ -75,6 +85,8 @@ rules:
7585
7686
Distributes data across time-based intervals. Each interval maps to a specific node named with a formatted date suffix.
7787
88+
Use `IntervalTimeline` when table names encode time periods such as day, month, or hour. It is also appropriate when a SnowflakeId can be converted back into event time.
89+
7890
### Usage
7991

8092
```java
@@ -213,12 +225,30 @@ Range queries are often repeated (e.g., querying "last 7 days" across many reque
213225
| High QPS range queries | CachedSharding + any | Cache avoids recomputation |
214226
| Auto-increment / SegmentId as key | ModCycle | Even distribution of monotonic IDs |
215227

228+
## Validation Checklist
229+
230+
Use a small routing matrix before finalizing a rule:
231+
232+
- One exact key routes to exactly one expected node.
233+
- An `IN` query routes to the union of expected nodes.
234+
- A range query covers all boundary nodes and no unrelated nodes when possible.
235+
- Values outside an `IntervalTimeline` effective range fail intentionally.
236+
- Snowflake timestamp extraction uses the same epoch and timestamp bits as the generator.
237+
- The ShardingSphere `actualDataNodes` expression matches every possible CosId effective node.
238+
216239
## Key Design Principles
217240

218241
1. **Precise + Range**: Every algorithm supports both single-value and range sharding. ShardingSphere uses precise for `=` and `IN`, and range for `BETWEEN`, `>`, `<`.
219-
220242
2. **Effective nodes**: `getEffectiveNodes()` returns all possible target nodes. This is used by ShardingSphere for routing optimization.
221-
222243
3. **Thread safety**: All sharding implementations are thread-safe (`@ThreadSafe`).
244+
4. **Interval bounds**: `IntervalTimeline` requires an explicit effective time range. Values outside this range throw `IllegalArgumentException`.
245+
5. **Generator alignment**: When the sharding key is a CosId-generated ID, keep the generator epoch, timestamp unit, and converter settings aligned with the sharding rule.
246+
247+
## Response Template
248+
249+
When answering a sharding request, include:
223250

224-
4. **Interval bounds**: IntervalTimeline requires an explicit effective time range. Values outside this range throw `IllegalArgumentException`.
251+
1. The selected algorithm and why it fits the sharding key.
252+
2. The expected table/database naming pattern.
253+
3. A concise Java or ShardingSphere YAML example.
254+
4. A routing test matrix for exact, `IN`, and range queries.
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
interface:
2+
display_name: "CosId Sharding"
3+
short_description: "Design CosId ShardingSphere rules"
4+
default_prompt: "Use $cosid-sharding to design CosId sharding rules for my database tables."

skills/cosid-spring-boot/SKILL.md

Lines changed: 33 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,21 @@
11
---
22
name: cosid-spring-boot
3-
description: Guide for integrating CosId distributed ID generator with Spring Boot. Use this skill whenever the user mentions CosId, distributed ID generation, SnowflakeId, SegmentId, SegmentChainId, CosIdGenerator, machine ID allocation, or needs help configuring ID generation in a Spring Boot application. Also use when the user asks about ID conversion (Radix62, Radix36, SnowflakeFriendly), sharding with CosId, or configuring machine ID distributors (Redis, JDBC, MongoDB, ZooKeeper) for Spring Boot. Triggers on cosid YAML configuration, application.yml ID setup, or any CosId Spring Boot starter questions.
3+
description: Configure CosId in Spring Boot applications with cosid-spring-boot-starter. Use when the user works with application.yml, Gradle or Maven dependencies, starter feature variants, Redis/JDBC/MongoDB/ZooKeeper/proxy distributors, SnowflakeId, SegmentId, SegmentChainId, CosIdGenerator, @CosId, IdGeneratorProvider, ID converters, machine guarder settings, clock-backwards synchronization, or Actuator endpoints in a Spring Boot service.
44
---
55

66
# CosId Spring Boot Integration
77

88
CosId is a universal, flexible, high-performance distributed ID generator for Java 17+. The Spring Boot starter (`cosid-spring-boot-starter`) provides auto-configuration for all ID generation strategies.
99

10+
## Workflow
11+
12+
1. Confirm the user's Spring Boot and CosId major versions. CosId 2.x targets Spring Boot 3.x and Java 17; CosId 3.x targets Spring Boot 4.x and Java 17.
13+
2. Choose the ID strategy. Use `$cosid-strategy-guide` first when the user has not chosen between SnowflakeId, SegmentId, SegmentChainId, and CosIdGenerator.
14+
3. Select the distributor and starter capability needed by the deployment: Redis, JDBC, MongoDB, ZooKeeper, proxy, manual, or StatefulSet.
15+
4. Provide the smallest working YAML for the selected strategy and backend.
16+
5. Show how the application consumes the generator: shared bean, named provider, or `@CosId`.
17+
6. Add validation guidance for uniqueness, ordering, machine ID ownership, segment allocation, and Actuator visibility.
18+
1019
## Dependency Setup
1120

1221
Add the BOM and starter to your `build.gradle`:
@@ -16,7 +25,7 @@ dependencies {
1625
implementation platform("me.ahoo.cosid:cosid-bom:${cosidVersion}")
1726
implementation "me.ahoo.cosid:cosid-spring-boot-starter"
1827
19-
// Add exactly ONE distributor backend based on your infrastructure:
28+
// Add the distributor backend needed by your infrastructure:
2029
implementation "me.ahoo.cosid:cosid-spring-boot-starter:springRedisSupport" // Redis
2130
// implementation "me.ahoo.cosid:cosid-spring-boot-starter:jdbcSupport" // JDBC/MySQL
2231
// implementation "me.ahoo.cosid:cosid-spring-boot-starter:mongoSupport" // MongoDB
@@ -68,8 +77,9 @@ There are 4 ID generation strategies in CosId. The right choice depends on your
6877

6978
- **Need maximum performance and have Redis/JDBC available?** → SegmentChainId (default segment mode)
7079
- **Need time-sortable IDs across machines?** → SnowflakeId
71-
- **Simple standalone app?** → CosIdGenerator (no external dependencies)
80+
- **Need compact string IDs or a large machine-ID design space?** → CosIdGenerator
7281
- **Database-friendly monotonic IDs?** → SegmentId or SegmentChainId
82+
- **Need only strategy selection?** → Use `$cosid-strategy-guide` before writing YAML
7383

7484
## Configuration Templates
7585

@@ -459,3 +469,23 @@ management:
459469
```
460470

461471
The `cosid` endpoint shows all registered ID generators and their stats.
472+
473+
## Validation Checklist
474+
475+
- Run a focused Spring Boot test that loads the application context with the chosen backend capability.
476+
- Generate IDs concurrently and assert uniqueness.
477+
- For SnowflakeId, verify machine ID allocation and clock-backwards settings.
478+
- For SegmentId/SegmentChainId, verify the segment distributor initializes the `cosid` table or backend state.
479+
- For converters, assert the expected prefix, padding, radix, and string length.
480+
- For shared beans, assert `IdGenerator` or `StringIdGenerator` resolves to the intended provider.
481+
- For production services, expose and inspect the CosId Actuator endpoint when actuator support is enabled.
482+
483+
## Response Template
484+
485+
When answering a Spring Boot integration request, include:
486+
487+
1. Dependency coordinates and the required backend capability.
488+
2. Minimal `application.yml` for the selected generator.
489+
3. Code snippet for injection or `@CosId`.
490+
4. Operational notes for machine ID, clock, state storage, and monitoring.
491+
5. A small test or verification command the user can run.
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
interface:
2+
display_name: "CosId Spring Boot"
3+
short_description: "Configure CosId Spring Boot starter"
4+
default_prompt: "Use $cosid-spring-boot to configure CosId in my Spring Boot application."

0 commit comments

Comments
 (0)