sledge
sledge2w ago

Persisting state for incrementing counter

I am using getResource and setResource for persisting a counter value across script executions. Here is the code:
type CPersistedCounter = {
lastValue: number,
updatedAt: number
}

export class IncrementingCounter {
private resourcePath: string;
private maxId: number;

constructor(resourcePath: string, maxId: number) {
this.resourcePath = resourcePath;
this.maxId = maxId;
}

async getNextId(): Promise<number> {
let currentState: CPersistedCounter;
try {
currentState = await wmill.getResource(this.resourcePath);
} catch {
// If the resource doesn't exist, throw an error
throw new Error(`Resource ${this.resourcePath} not found in workspace`);
}

const newId = (currentState.lastValue + 1) % this.maxId;
const newState: CPersistedCounter = {
updatedAt: Date.now(),
lastValue: newId,
};

// Save the updated state to the Windmill resource - do not need to await because it can proceed in background
wmill.setResource(newState, this.resourcePath);

return newId;
}
}
type CPersistedCounter = {
lastValue: number,
updatedAt: number
}

export class IncrementingCounter {
private resourcePath: string;
private maxId: number;

constructor(resourcePath: string, maxId: number) {
this.resourcePath = resourcePath;
this.maxId = maxId;
}

async getNextId(): Promise<number> {
let currentState: CPersistedCounter;
try {
currentState = await wmill.getResource(this.resourcePath);
} catch {
// If the resource doesn't exist, throw an error
throw new Error(`Resource ${this.resourcePath} not found in workspace`);
}

const newId = (currentState.lastValue + 1) % this.maxId;
const newState: CPersistedCounter = {
updatedAt: Date.now(),
lastValue: newId,
};

// Save the updated state to the Windmill resource - do not need to await because it can proceed in background
wmill.setResource(newState, this.resourcePath);

return newId;
}
}
I did not use get/setState for a variety of reasons, but maybe that will have to change. The problem I just now realized is that this particular resource is now part of my git repo, which means the running incremented counter will get overwritten with each deploy. Our syncs only include --skip-secrets right now. Maybe the answer is that we should just not include any resources in our repo at all? I think that is it. (I'm answering my own question as I'm describing the problem). So - is that best practice - no resources or secrets go into the repo?
1 Reply
sledge
sledgeOP2w ago
I tried adding --skip-resources to our command usage - it resulted in the resource types that we had in the repo getting deleted, but none of the resources, they all stayed there. I did a clean sync pull and that had no resources. Ahhh, looks like maybe deleting the wmill-lock.yaml was the answer.

Did you find this page helpful?